[英]Error on DateTime.ParseExact
我在oracle數據庫中有一個查詢的日期。 這個日期看起來像:
5/3/2016 (after I remove the time portion)
我嘗試將此日期轉換為DateTime
。 我在用:
ParseExact(String, String, IFormatProvider)
我做錯了,我無法弄清楚。 我的代碼如下所示。 請注意,如上所述,名為“ res”的變量的值為5/3/2016
try {
while(reader.Read()) {
string res = reader[0].ToString().Substring(0, 8);
mailer.SendSmtpMail4dev("Result: " + res);
mailer.SendSmtpMail4dev("Result: " + DateTime.ParseExact(res, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture));
}
} catch(Exception e) { ...
for DateTime.ParseExact
輸入字符串的格式和格式字符串應相同,因此請使用:
DateTime.ParseExact(res, "d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture);
在你的情況下,提供的日期是5/3/2016
和您指定的格式為"dd-MM-yyyy"
這種轉換是不可能的。 如果您需要更改格式,則可以執行以下操作:
string res = "5/2/2016";
DateTime givenDate = DateTime.ParseExact(res, "d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture);
string newFormatedDate = givenDate.ToString("dd-MM-yyyy");
由於您的res
日期為dd/MM/yyyy
格式,但是您嘗試將其轉換為dd-MM-yyyy
,所以在DateTime.ParseExact()
您必須提供相同格式的datetime和format字符串,正確的代碼將像這樣
mailer.SendSmtpMail4dev("Result: " + DateTime.ParseExact(res, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture).ToString("dd-MM-yyyy"));
采用:
DateTime.ParseExact(res, "d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture);
有關詳細信息,請參閱MSDN文章 。
采用
DateTime.ParseExact(res, "d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture).ToString("dd-MM-yyyy")
如果有日期,為什么將其轉換為String
// What if server's NLS_* settings are changed? What does 8 stand for?
reader[0].ToString().Substring(0, 8);
然后再次Parse
? 如果reader[0]
是日期,請使用DateTime
:
try {
while(reader.Read()) {
// 0th field is date, then treat it as being date
DateTime date = Convert.ToDateTime(reader[0]);
//TODO: put the right formats here
mailer.SendSmtpMail4dev("Result: " + date.ToString("dd-MM-yyyy"));
mailer.SendSmtpMail4dev("Result: " + date.ToString("dd-MM-yyyy"));
}
}
catch(Exception e) {
...
}
我的問題的解決方案已在上面標記,但是我只想聲明一些重要的內容,以便其他人可以節省一些時間。 一些建議的解決方案建議這樣做: DateTime.ParseExact(res, "dd/MM/yyyy" ...)
在網絡上的許多其他示例中似乎也是如此,所以我並不是說這是錯誤的。 然而。 在我嘗試這樣做之前,我花了一些時間對我不起作用:
DateTime.ParseExact(res, "d/M/yyyy" ...)
請注意,在后面的解決方案中,只有一個d和一個M。但是,正如大家指出的那樣,我的主要問題可能是我在使用:
"dd-MM-yyyy" instead of "dd/MM/yyyy" (which is the same format as the oracle value)
希望這可以節省您一些時間
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.