14

How to format a JSON date obtained from twitter to a C# DateTime ? Here is the format of the date I receive :

"Tue, 19 Feb 2013 13:06:17 +0000"

Can I do it with JSON.NET ?

2

5 Answers 5

20

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
2
  • Thanks for link, next time please post date format here, parsing twitter date is a common task.
    – Nanoc
    Jul 11, 2014 at 10:50
  • The date format string in this example is incorrect. 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. The correct format string is "ddd MMM dd HH:mm:ss zzz yyyy". Custom Date and Time Format Strings in .NET Aug 13, 2018 at 13:02
10

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

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

1

It's DateTimeOffset not DateTime. Following should work.

DateTimeOffset parsed = DateTimeOffset.Parse("Tue, 19 Feb 2013 13:06:17 +0000");
0

I needed a PowerShell variant of these answers and the following worked for me.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.