如何将从twitter获得的JSON日期格式化为C# DateTime?
"Tue, 19 Feb 2013 13:06:17 +0000"
我可以用JSON.NET做吗?
使用以下方法解决 DateTime.ParseExact
-> http:/blog.kevinyu.org201207handling-json-in-net.html
链接更新。 链接的博文已离线。它的缓存副本仍然可以被引用 通过 "时光机 "互联网档案馆.
从博文中复制出来的常见.NET代码是。
public const string Const_TwitterDateTemplate = "ddd MMM dd HH:mm:ss +ffff yyyy";
DateTime createdAt = DateTime.ParseExact((string)jo["created_at"],
Const_TwitterDateTemplate, new System.Globalization.CultureInfo("en-US"));
其中
jo
是一个JSON对象,代表 created_at
日期属性,但实际上Twitter的日期字符串会进入这个参数。流的答案中的部分代码。
public const string Const_TwitterDateTemplate = "ddd MMM dd HH:mm:ss +ffff yyyy";
DateTime createdAt = DateTime.ParseExact((string)jo["created_at"], Const_TwitterDateTemplate, new System.Globalization.CultureInfo("en-US"));
上面使用fffff格式指定符的答案似乎返回了正确的结果,但技术上这是错误的。fffff是万分之一秒的格式指定符,Twitter日期中的+0000表示与UTC偏移的小时和分钟。请看下面的格式。
string twitterTime = "Wed Feb 22 15:49:01 +0000 2017";
string twitterTimeformat = "ddd MMM dd HH:mm:ss zzz yyyy";
DateTime dateTime = DateTime.ParseExact(twitterTime, twitterTimeformat,
CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
Console.WriteLine(dateTime);
结果: 2222017 3: 49: 01 PM
如果需要的话,你可以编辑DateTimeStyles枚举来返回当地时间而不是UTC。
是DateTimeOffset而不是DateTime。下面的答案应该可以。
DateTimeOffset parsed = DateTimeOffset.Parse("Tue, 19 Feb 2013 13:06:17 +0000");
我需要这些答案的PowerShell变体,下面的答案对我有用。
PS> $Created_At = 'Fri Jun 05 18:15:48 +0000 2020'
PS> [datetime]::ParseExact($Created_At,'ddd MMM dd HH:mm:ss zzz yyyy',(Get-Culture))
Friday, June 5, 2020 1:15:48 PM