DateTime.TryParse解析错误的格式
问题描述:
我试图解析字符串(从充满英语的日期格式一个文本框)使用此代码为DateTime:DateTime.TryParse解析错误的格式
DateTime dt;
if (DateTime.TryParseExact(Text, DateTimeFormat, System.Threading.Thread.CurrentThread.CurrentCulture, DateTimeStyles.AssumeLocal, out dt))
{
logger.Trace("LOCALE: {0} ", System.Threading.Thread.CurrentThread.CurrentCulture);
logger.Trace("DateTimeFormat: {0} ", DateTimeFormat);
logger.Trace("CurrentCulture ShortDatePattern: {0} ", System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern);
logger.Trace("Text: {0} ", Text);
logger.Trace("result of TryParse: {0} ", dt);
return dt;
}
但是在我的记录器输出为:
LOCALE: en-US
DateTimeFormat ShortDatePattern: M/d/yyyy
CurrentCulture ShortDatePattern: M/d/yyyy
Text: 8/31/2012
result of TryParse: 31-8-2012 0:00:00
我完全卡住为什么会发生这种情况。
在一个单独的控制台应用程序中使用此代码的工作:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
string text = @"8/31/2012";
DateTime date;
string dateTimeFormat = @"M/d/yyyy";
bool parseOk = DateTime.TryParseExact(text, dateTimeFormat, Thread.CurrentThread.CurrentCulture, DateTimeStyles.AssumeLocal, out date);
额外的信息:
- 系统:Windows 7旗舰版EN
- 非Unicode系统语言:英语
- web.config system.web:
问题: 问题是我想要的日期是在格式为“M/d/YYYY”,而是它被解析为“DD-MM-YYYY”
答
您还没有导致无效日期为日志条目指定了一个输出字符串,因此它将使用默认值(基于当前文化)。
因此,而不是:
logger.Trace("result of TryParse: {0} ", dt);
用途:
logger.Trace("result of TryParse: {0} ", dt.ToString("M/dd/yyyy"));
或者:
logger.Trace("result of TryParse: {0} ", dt.ToShortDateString());
我没有看到你的记录任何错误。文本正确解析...出了什么问题?或者您想以格式M/d/yyyy再次在记录器中打印日期时间? – JleruOHeP 2012-08-17 11:30:56
什么是错的,在我看来,日期被正确解析。 – 2012-08-17 11:31:56
其格式问题。 OP要M/DD/YYYY,但输出为DD-M-YYYY – 2012-08-17 11:33:01