DateTime.ParseExact字符串格式不断抛出错误字符串、抛出、错误、格式

2023-09-03 22:37:26 作者:唱着咆哮炸学校

我有一个字符串再$ P $日期时间psentation看起来是这样的:

I have a string representation of DateTime that looks like this:

2011-05-25T16:42:17.156Z

我已经试过,没有任何运气如下:

I have tried the following without any luck:

DateTime.ParseExact(formatted, "yyyy-MM-ddThh:mm:ss.fffZ", CultureInfo.CurrentCulture);
DateTime.ParseExact(formatted, "yyyy-MM-dd hh:mm:ss.fff", CultureInfo.CurrentCulture);
DateTime.ParseExact(formatted, CultureInfo.CurrentCulture.DateTimeFormat.GetAllDateTimePatterns(), CultureInfo.CurrentCulture, DateTimeStyles.AssumeUniversal);
DateTime.ParseExact(formatted, CultureInfo.CurrentCulture.DateTimeFormat.GetAllDateTimePatterns(), CultureInfo.CurrentCulture, DateTimeStyles.None);

所有这些给了错误:

All of these give the error:

String was not recognized as a valid DateTime.

标准DateTime.Parse似乎工作,虽然性能方面的原因,我们正在探索ParseExact。这似乎是应该pretty的直线前进,但似乎无法得到它的工作。

Standard DateTime.Parse appears to work, though for performance reasons we are exploring ParseExact. This seems like it should be pretty straight forward, but can't seem to get it to work.

推荐答案

使用HH,而不是HH 24小时格式。这应该工作:

Use HH instead of hh for 24 hour format. This should work:

DateTime.ParseExact(formatted, "yyyy-MM-ddTHH:mm:ss.fffZ",
                    CultureInfo.CurrentCulture);

您的确定的要使用当前的文化,而不是固定区域性的关系吗?

Are you sure you want to use the current culture rather than the invariant culture though?