[英]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.