2013-02-19 14 views
10

Come formattare una data JSON ottenuta da Twitter ad un C# DateTime? Ecco il formato della data che ricevo:Data JSON dal formato tweeter a C#

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

Posso farlo con JSON.NET?

+0

cosa succede quando si fa 'DateTime.Parse ("Tue, 19 Feb 2013 13:06:17 +0000")'? –

+0

Duplicato http://stackoverflow.com/questions/1551662/c-sharp-parse-json-date – Pete

risposta

1

Non è DateTimeOffset DateTime. In seguito dovrebbe funzionare.

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

Parte del codice dalla risposta di flusso.

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

Le risposte precedenti che utilizzano l'identificatore di formato ffff sembrano restituire il risultato corretto, ma tecnicamente questo è sbagliato. ffff è lo specificatore di formato per dieci millesimi di secondo e il +0000 in una data di Twitter indica l'offset di ore e minuti da UTC. Vedere il seguente formato:

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

Risultato: 2017/02/22 15:49:01

è possibile modificare il DateTimeStyles di enumerazione per restituire l'ora locale invece di UTC, se desiderato.

Custom Date and Time Format Strings

DateTimeStyles Enumeration