1

应该如何格式化日期/时间字符串,以便可以DateTime.TryParseExact使用“U”格式字符串和DateTimeStyles.AdjustToUniversal?换句话说,在下面的代码timestampStringisDateTime设置为什么是有效的?true

string timestampString = "...";

DateTime timestamp;
bool isDateTime = DateTime.TryParseExact(
    timestampString, "U", null, DateTimeStyles.AdjustToUniversal, out timestamp);
4

2 回答 2

5

以下是 en-US 文化的示例:

string timestampString = "Saturday, April 20, 2013 9:00:00 PM";

DateTime timestamp;
bool isDateTime = DateTime.TryParseExact(timestampString, "U", null,
    DateTimeStyles.AdjustToUniversal, out timestamp);

Console.WriteLine(isDateTime);     // True
Console.WriteLine(timestamp);      // 4/20/2013 9:00:00 PM
Console.WriteLine(timestamp.Kind); // Utc

如 MSDN 库中的标准日期和时间格式字符串主题下所述,“U”表示由DateTimeFormatInfo.FullDateTimePattern属性定义的格式,并自动转换为 UTC。对于 en-US,此格式为"dddd, MMMM d, yyyy h:mm:ss tt".

于 2013-04-21T04:11:06.517 回答
1

From this MSDN post:

AdjustToUniversal Parses the string represented by input and, if necessary, converts it to UTC. It is equivalent to parsing a string and then calling the DateTimeOffset.ToUniversalTime method of the returned DateTimeOffset object.

So, try first to parse your date.

I am not sure the format "U" is valid for date time. For example, I did not found it on MSDN date time formats page

于 2013-04-21T04:08:22.723 回答