【发布时间】:2014-08-06 21:49:48
【问题描述】:
将DateTime.MinValue 存储到 MS Access 中的字段(作为日期/时间类型)时遇到问题。在存储到数据库之前打印出来,我得到“1/1/0001 12:00:00 AM”,这是预期的。但是,从数据库中检索到相同的值后,我得到“1/1/2001 12:00:00 AM”(注意 2001 年而不是 1 年)。
这显然是错误的!有人有什么想法吗?
请注意,我使用 DateTime.MinValue 作为有人建议的无效日期/时间,因为 DateTime 不能为空值。
写入数据库的代码是:
public static bool StartNow(string profileID, string startNotes)
{
DateTime now = DateTime.Now;
OleDbCommand cmd = new OleDbCommand("SELECT * FROM shifts WHERE profile_id=@profile_id AND closed=false;");
cmd.Parameters.AddWithValue("@profile_id", profileID);
// A new shift should NEVER be started with another open shift.
OleDbDataReader reader = Database.Read(cmd);
if (reader.HasRows)
return false;
cmd = new OleDbCommand("INSERT INTO shifts(profile_id, start, stop, start_log, stop_log, start_notes, stop_notes, closed) VALUES(@profile_id, @start, @stop, @start_log, @stop_log, @start_notes, @stop_notes, @closed);");
cmd.Parameters.AddWithValue("@profile_id", profileID);
cmd.Parameters.AddWithValue("@start", RoundUp(now, 30).ToString());
cmd.Parameters.AddWithValue("@stop", DateTime.MinValue);
cmd.Parameters.AddWithValue("@start_log", now.ToString());
cmd.Parameters.AddWithValue("@stop_log", DateTime.MinValue);
cmd.Parameters.AddWithValue("@start_notes", startNotes);
cmd.Parameters.AddWithValue("@stop_notes", "");
cmd.Parameters.AddWithValue("@closed", false);
// TODO: need to set default values for stop, stop_log and stop_notes
return Database.Write(cmd) == 1 ? true : false;
}
这是读取日期和时间的代码:
public static List<ShiftView> TodaysShifts()
{
List<ShiftView> shifts = new List<ShiftView>();
// INFO: Not intended to retrieve a lot of records as there is no caching....
OleDbCommand cmd = new OleDbCommand("SELECT profiles.profile_id, profiles.full_name, shifts.start, shifts.stop, shifts.start_log, shifts.stop_log, shifts.start_notes, shifts.stop_notes FROM shifts, profiles WHERE (shifts.start>=@today) AND (shifts.profile_id=profiles.profile_id);");
cmd.Parameters.AddWithValue("@today", DateTime.Today);
OleDbDataReader reader = Database.Read(cmd);
while(reader.Read())
{
shifts.Add(new ShiftView(
reader.GetString(reader.GetOrdinal("profile_id")),
reader.GetString(reader.GetOrdinal("full_name")),
reader.GetDateTime(reader.GetOrdinal("start")),
reader.GetDateTime(reader.GetOrdinal("stop")),
reader.GetDateTime(reader.GetOrdinal("start_log")),
reader.GetDateTime(reader.GetOrdinal("stop_log")),
reader.GetString(reader.GetOrdinal("start_notes")),
reader.GetString(reader.GetOrdinal("stop_notes"))
));
}
return shifts;
}
【问题讨论】: