【问题标题】:DateTime.TryParse Parses to wrong formatDateTime.TryParse 解析为错误的格式
【发布时间】:2012-08-17 11:26:41
【问题描述】:

我正在尝试使用以下代码将字符串(从一个用英文日期格式填充的文本框)解析为 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;
}

但是我的记录器中的输出是:

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 Ultimate EN
  • 非 Unicode 的系统语言:英语
  • web.config system.web:

问题: 问题是我希望日期的格式为“M/d/yyyy”,但它被解析为“dd-mm-yyyy”,这导致日期无效

【问题讨论】:

  • 我在您的记录器中看不到任何错误。文本被正确解析......出了什么问题?或者您想在记录器中以 M/d/yyyy 格式再次打印 DateTime?
  • 怎么了,在我看来日期解析正确。
  • 它的格式问题。 OP 想要 M/DD/YYYY 但输出是 DD-M-YYYY
  • .CurrentUICulture 是什么?看起来 DateTime 解析正常。您只是以意外的格式输出它。 (虽然我自己来自英国,但不会说格式不对!)
  • 不知何故,输出格式是荷兰语 (nl) 语言环境。

标签: c# asp.net datetime


【解决方案1】:

您尚未为日志条目指定输出字符串,因此它将使用默认字符串(基于当前文化)。

所以,而不是:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-03
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-05
    • 2020-04-05
    相关资源
    最近更新 更多