JSON日期从tweeter到C#格式

flo*_*low 11 c# json date-format json.net

如何格式化从twitter获得的JSON日期到C#DateTime?这是我收到的日期格式:

"Tue, 19 Feb 2013 13:06:17 +0000"
Run Code Online (Sandbox Code Playgroud)

我可以用JSON.NET吗?

flo*_*low 16

解决了使用 DateTime.ParseExact

- > http://blog.kevinyu.org/2012/07/handling-json-in-net.html

链接更新:链接的博客帖子处于脱机状态.缓存副本仍然可以通过Way Back Machine Internet Archive引用.

从博客文章复制的常见.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"));
Run Code Online (Sandbox Code Playgroud)

哪里

  • variable jo是一个表示created_at日期属性的JSON对象,但实际上Twitter日期字符串会进入此参数


dda*_*san 10

来自流程答案的部分代码.

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"));
Run Code Online (Sandbox Code Playgroud)


Chr*_*ter 6

上面使用 ffff 格式说明符的答案似乎返回了正确的结果,但从技术上讲这是错误的。ffff 是千分之一秒的格式说明符,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);
Run Code Online (Sandbox Code Playgroud)

结果:2/22/2017 3:49:01 PM

如果需要,您可以编辑 DateTimeStyles 枚举以返回本地时间而不是 UTC。

自定义日期和时间格式字符串

日期时间样式枚举