【问题标题】:Datetime.parseexact throws errorDatetime.parseexact 抛出错误
【发布时间】:2014-09-10 09:15:37
【问题描述】:

我有以下代码

输入日期时间值为"2014/09/11 8:06 AM" 日期格式为"yyyy/MM/dd h:mm a"

CultureInfo culture = CultureInfo.InvariantCulture;

string dateforamat = string.Concat(date, " ", time);

returnValue = DateTime.ParseExact(inputDateTime, dateforamat, culture);

我收到格式异常

【问题讨论】:

  • 请注意,日期格式字符串中的原始斜杠 (/) 字符实际上代表 date separator,具体取决于您指定的区域性。我建议用单引号 (yyyy'/'MM'/'dd) 将斜线括起来,以避免长期出现意外。
  • @FrédéricHamidi:你可以用CultureInfo.InvariantCulture 来阻止这种情况,OP 已经这样做了。
  • @Tim,如果提问者直接通过InvariantCulture,就像您在回答中所做的那样,我不会说什么。但是,将其存储在局部变量中让我认为它可能会在现在或将来调用 ParseExact() 之前被修改。

标签: c# asp.net wpf date datetime


【解决方案1】:

使用tt 而不是a

DateTime.ParseExact("2014/09/11 8:06 AM", "yyyy/MM/dd h:mm tt", CultureInfo.InvariantCulture);

阅读:The "tt" Custom Format Specifier

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 1970-01-01
    相关资源
    最近更新 更多