简体   繁体   English

DateTime.TryParse解析为错误的格式

[英]DateTime.TryParse Parses to wrong format

I am trying to parse a string (from a Textbox filled with english dateformat) to a DateTime using this code: 我正在尝试使用以下代码将字符串(从充满英语dateformat的文本框)解析为DateTime:

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;
}

However the output in my logger is: 但是我的记录器中的输出是:

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 

I am completly stuck why this is happening. 我完全被困住了,为什么会这样。

Using this code in a seperate console application DOES work: 在单独的控制台应用程序中使用此代码可以正常工作:

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);

extra info: 额外信息:

  • system: Windows 7 Ultimate EN 系统:Windows 7 Ultimate EN
  • system language for non-UniCode: english 非UniCode的系统语言:英文
  • web.config system.web: web.config system.web:

PROBLEM: The problem is I want the date to be in the format "M/d/yyyy" but instead it is parsed to "dd-mm-yyyy" which results in an invalid date 问题:问题是我希望日期格式为“ M / d / yyyy”,但是将其解析为“ dd-mm-yyyy”,这导致无效的日期

You have not specified an output string for the log entry, so it will use the default one (based on the current culture). 您尚未为日志条目指定输出字符串,因此它将使用默认字符串(基于当前区域性)。

So, instead of: 因此,代替:

logger.Trace("result of TryParse: {0} ", dt);

Use: 采用:

logger.Trace("result of TryParse: {0} ", dt.ToString("M/dd/yyyy"));

Or: 要么:

logger.Trace("result of TryParse: {0} ", dt.ToShortDateString());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM