2010-01-04 16 views
10

C'è un modo semplice per convertire il timestamp che si ottiene da Twitter in unix ora o minuti da adesso? Potrei analizzare attraverso la stringa e convertire tutto da solo, ma spero che ci sia un modo per convertire che non ne ha bisogno. Ecco un esempio di un elemento created_at con un timestamp.API iPhone + Twitter: conversione del tempo?

domenica da marzo 18 06:42:26 +0000 2007

risposta

22

È possibile utilizzare NSDateFormatter con qualcosa di simile:


NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; 
[dateFormatter setLocale:usLocale]; 
[usLocale release]; 
[dateFormatter setDateStyle:NSDateFormatterLongStyle]; 
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4]; 

// see http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns 
[dateFormatter setDateFormat: @"EEE MMM dd HH:mm:ss Z yyyy"]; 

NSDate *date = [dateFormatter dateFromString:[currentDict objectForKey:@"created_at"]]; 
[dateFormatter release]; 

NSTimeInterval seconds = [date timeIntervalSince1970]; 
+0

Grazie, funziona perfettamente! – self

+2

Anche questo è in parte anche sbagliato! La creazione di un oggetto NSDateFormatter è piuttosto pesante, quindi rendilo statico, o rendilo un ivar quando è possibile. –

0

File una richiesta di funzionalità con Apple e far loro sapere che si desidera questa funzionalità su iPhone. NSDateFormatter fornisce un metodo init legacy che accetta un flag booleano che indica che vuoi analizzare la lingua naturale, ma è disponibile solo su OS X. Wil Shipley ha scritto un interesting post un po 'indietro su questa funzionalità nel contesto di euristica e fattori umani.

Non sembra probabile che Apple fornirà questa funzionalità come questa nota indicherebbe dal NSDateFormatter docs:

iPhone OS Nota: iPhone OS supporta solo il comportamento 10.4+. I metodi e le stringhe di formato 10.0-style non sono disponibili su iPhone OS .

In altre parole, penso che dovrai analizzarlo da solo.

2

Ho strugeling con questo tutto il giorno, ma questa discussione mi ha aiutato a trovare una soluzione.

Ecco come faccio a convertire l'attributo Twitter "created_at" in un NSDATE;

NSDateFormatter *fromTwitter = [[NSDateFormatter alloc] init]; 
// here we set the DateFormat - note the quotes around +0000 
[fromTwitter setDateFormat:@"EEE MMM dd HH:mm:ss '+0000' yyyy"]; 
// We need to set the locale to english - since the day- and month-names are in english 
[fromTwitter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en-US"]]; 

NSString *dateString = [item objectForKey:@"created_at"]; 
NSDate *tweetedDate = [fromTwitter dateFromString:dateString]; 

Spero che qualcuno lo troverà utile.

+0

ZOMG grazie che funziona! Trovato 5 altri formati che non hanno funzionato. La chiave sembra essere il locale che a tutti gli altri sembra mancare. –