JSON date from tweeter to C# format

Solved with use of DateTime.ParseExact

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

Link Update: the linked blog post is offline. It cached copy can still be referenced via the Way Back Machine Internet Archive.

The common .NET code copied from the blog post is:

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"));

where

  • variable jo is a JSON object representing the created_at date property, but effectively the Twitter date string goes into this parameter

Part of code from flow's answer.

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"));

The answers above that use the ffff format specifier seem to return the correct result, but technically this is wrong. ffff is the format specifier for ten thousandths of a second, and the +0000 in a Twitter date indicates the hours and minutes offset from UTC. See the format below:

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);

Result: 2/22/2017 3:49:01 PM

You can edit the DateTimeStyles enumeration to return the local time instead of UTC if desired.

Custom Date and Time Format Strings

DateTimeStyles Enumeration