无法解析格式为2013-09-17T05:15:27.947的日期字符串。

7

我正在尝试解析以下格式的日期:

2013-09-17T05:15:27.947

这是我的代码:

String MessageRecieptDate = messageReceiptDate.Replace("T", " ").Remove(messageReceiptDate.Length-4);
DateTime dt = new DateTime();
IFormatProvider culture = new CultureInfo("en-US");
dt = DateTime.ParseExact(MessageRecieptDate, "dd MMM", culture);

但是每次出现格式异常。看起来我漏掉了一些基础的东西。

ParseExact的性能比Parse更高,但您必须提供匹配的字符串格式。您可以直接调用Parse - Dan
什么是“某些格式异常”? - Dour High Arch
@DourHighArch 不要太天真,如果问题不可理解,这里的人们就无法回答它。 - Ankit
6个回答

10

我不知道为什么你在使用"dd MMM"作为格式字符串,当你的日期是"2014-02-03T19:00:00"时。这两种格式没有任何共同点。

您输入的正确格式字符串是"yyyy-MM-ddTHH:mm:ss"

string value = "2014-02-03T19:00:00";
DateTime dateValue = DateTime.ParseExact(value, "yyyy-MM-ddTHH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);

哦,我以为那是输出格式,原来是输入字符串的格式。谢谢 :) - Ankit

4

应该正常工作的内容:

//without ParseExact
var t1= DateTime.Parse(dt);

//you don't know how many milliseconds will be in your string, 
//and want absolutely use ParseExact anyway
var t2= DateTime.ParseExact(dt.PadRight(27, '0'), "o", culture);

//you know you'll always have 3 chars for milliseconds.
var t3= DateTime.ParseExact(dt, "yyyy-MM-ddTHH:mm:ss.fff", culture);

我不确定ticks中会有多少个字符,所以除了提供f、ff、fff格式字符串之外,还有其他的方法吗? - Ankit
@ay89 看看我的第二个版本。PadRight会在你的字符串末尾添加必要数量的'0'。但是,说实话,如果你的字符串不是“精确”的,使用ParseExact有点奇怪,你应该使用Parse... - Raphaël Althaus

3
Marcin的答案是正确的,但我想指出你问题的根源。

当你写代码时,

string MessageRecieptDate = messageReceiptDate.Replace("T", " ").Remove(messageReceiptDate.Length-4);

实际上,您在字符串中删除了太多内容。执行此行代码后,您的字符串将变为:
2014-02-03 19:0

尝试使用Remove(messageReceiptDate.Length - 3);代替。这将使您的字符串变为2014-02-03 19:00,正是我们想要的。
然后,您应该使用与2014-02-03 19:00完全匹配的yyyy-MM-dd HH:mm格式。
string messageReceiptDate = "2014-02-03T19:00:00";
string MessageRecieptDate = messageReceiptDate.Replace("T", " ").Remove(messageReceiptDate.Length - 3);
IFormatProvider culture = new CultureInfo("en-US");
DateTime dt = DateTime.ParseExact(MessageRecieptDate, "yyyy-MM-dd HH:mm", culture);
Console.WriteLine(dt);

输出结果将是:

2/3/2014 7:00:00 PM

这里有一个演示


实际上,这段代码的输出是:03/02/2014 19:00:00。这是否取决于本地设置? - dzookatz
1
@dzookatz 是的,这完全取决于您当前的文化日期格式设置。 - Soner Gönül

2
你的字符串格式完全错误:
你需要指定与输入字符串匹配的格式,即:"yyyy-MM-ddTHH:mm:ss"
 string MessageReceiptDate = "2014-02-03T19:00:00";
 var datex = DateTime.ParseExact(MessageReceiptDate, "yyyy-MM-ddTHH:mm:ss", culture);

2

使用DateTime.TryParseExact方法。

DateTime dateValue;
string dateString = "2013-09-17T05:15:27.947";
string[] formats= {"yyyy-MM-ddTHH:mm:ss"};
if(DateTime.TryParseExact(dateString, formats, 
                              new CultureInfo("en-US"), 
                              DateTimeStyles.None, 
                              out dateValue))
{
   //parsing successful
}

1

This line:

dt = DateTime.ParseExact(MessageRecieptDate, "dd MMM", culture);

日期格式有误。

应该像这样:

dt = DateTime.ParseExact(MessageRecieptDate, "yyyy-MM-ddTHH:mm:ss", culture);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接