[英]Trouble with DateTime.ParseExact
我正在研究提醒應用程序。 應用程序將提醒Date,Time和DateLastShown(在不同字段中)存儲在數據庫中,並將它們拉出以執行檢查。
所有日期均為“ d / MM / yyyy”格式。 我的問題是,當我從數據庫中提取日期並嘗試將其存儲回DateTime格式時,它們仍以“ M / d / yyyy”格式顯示,而這並不是應用程序的必需格式。
我本質上需要從數據庫中獲取值,然后進行一些檢查以確定是否是時候顯示提醒並這樣做。 似乎很簡單,也許我正在犯一些小錯誤。
以下是我的注釋代碼。 任何幫助真的很感激。
public void CheckReminders()
{
IQueryable<Reminder> reminders;
DateTime reminderDate;
DateTime reminderTime;
DateTime reminderLastShown;
DateTime todayDate;
DateTime timeNow;
while (true)
{
try
{
db = new StudioManagementEntities();
reminders = from r in db.Reminders
select r;
foreach (Reminder r in reminders)
{
if (r.Enabled == 1)
{
if (r.Recurring == 1)
{
// This is the code i was using before when the date was in "M/d/yyyy" format
// which seems to be default.
reminderTime = DateTime.Parse(r.Time);
timeNow = DateTime.Parse(DateTime.Now.ToLongTimeString());
if (r.DateLastShown != DateTime.Today.ToShortDateString() && timeNow >= reminderTime)
{
FrmReminder frmReminder = new FrmReminder(r.Id, true);
frmReminder.ShowDialog();
r.DateLastShown = DateTime.Today.ToShortDateString();
}
}
else
{
// Now i need to pass in "d/M/yyyy" format but the
// code seems to return in "M/d/yyyy" format.
reminderDate = DateTime.ParseExact(r.Date, "d/MM/yyyy", null);
// Even this returns in wrong format
reminderDate = DateTime.ParseExact("24/01/2013", "d/MM/yyyy", null);
// Have tried with CultureInfo.InvariantCulture too.
MessageBox.Show(reminderDate.ToString());
return;
if (
r.DateLastShown != DateTime.Today.Date.ToShortDateString() //&&
//r.Date == DateTime.ParseExact(DateTime.Today, "d/MM/yyyy", CultureInfo.InvariantCulture).ToString() //&&
//now.TimeOfDay.TotalSeconds >= reminderTime.TimeOfDay.TotalSeconds
)
{
FrmReminder frmReminder = new FrmReminder(r.Id, true);
frmReminder.ShowDialog();
r.DateLastShown = DateTime.Today.ToShortDateString();
}
}
}
}
db.SaveChanges();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
// Check every minute
Thread.Sleep(60000);
}
}
和數據庫表。
如果解析為date對象沒有出錯,則在調用.ToString()時,您的輸出僅存在問題。
從文檔:
ToString方法返回當前區域性所使用的日歷中日期和時間的字符串表示形式。
如果您需要用戶當前的區域性設置以外的其他功能,則可以在重載的ToString()方法中使用格式字符串來指定:
var reminderDate = DateTime.ParseExact("24/01/2013", "d/MM/yyyy", null);
MessageBox.Show(reminderDate.ToString("d/MM/yyyy"));
同樣,正如其他人在評論中指出的那樣,如果可能,您應該在數據庫中使用日期數據類型,而不是將值存儲為字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.