2012-06-16 10 views
20

Ho il seguente codice.NSDateFormatter in modalità 12 ore

NSDateFormatter *df = ...; 
[df setTimeZone:[NSTimeZone defaultTimeZone]]; 
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"]; 
NSDate * date = [df dateFromString:date_string]; //here is the problem 

Nella modalità 24 ore tutto è ok. Quando la modalità 12 ore è impostata sul dispositivo, stringFromDate restituisce null. Il formato di data_string è lo stesso anche per il formato di data e ora. Perché succede?

+0

in grado di visualizzare il valore u DATE_STRING! – Dinesh

+0

2012-06-16T10: 00: 47.436 + 0000 per esempio – Sergey

+0

Vedere [questo post] (http://stackoverflow.com/q/6613110/581994). –

risposta

30

cercare di impostare il locale in questo modo:

NSLocale *twelveHourLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; 
df.locale = twelveHourLocale; 

Per forzare invece a 24 ore, è possibile utilizzare:

NSLocale *twentyFour = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"]; 
+0

Vorrei forzare l'uso di dateformatter per ignorare la modalità 12 ore e utilizzare 24 ore su 24 tutte le volte. Quale identificatore di posizione dovrei usare? – Sergey

+0

it_IT -> NSLocale * formatterLocale = [[[allocazione NSLocale] initWithLocaleIdentifier: @ "en_GB"] autorelease]; – aleroot

+0

Brillante! Funziona come un fascino. – Fogmeister

49

Nei tuoi NSDateFormatter "yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"HH stand per 24 ore e hh sta per 12 ore

+0

Voglio ignorare le impostazioni di sistema di 12 ore e non so come – Sergey

+5

@Sergey quindi utilizzare ** hh ** invece di ** HH ** –

+1

Se imposto hh allora quando ricevo 14:55 non funzionerà – Sergey

6

modalità 12 ore a 24 ore modalità:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
[formatter setDateFormat:@"hh:mm a"]; 
NSDate *amPmDate = [formatter dateFromString:amPmHourString]; 
[formatter setDateFormat:@"HH:mm"]; 
NSString *24HourString = [formatter stringFromDate:amPmDate]]; 

Per la modalità modalità 24 ore su 12 ore solo fare il contrario

4
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
NSLocale *locale = [[[NSLocale alloc] 
       initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]; 
[dateFormat setLocale:locale]; 
Problemi correlati