2012-09-14 9 views
11

Ho una stringa "2012-09-16 23:59:59 JST" Voglio convertire questa stringa di data in NSDate.NSData dalla stringa

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss Z"]; 
NSDate *capturedStartDate = [dateFormatter dateFromString: @"2012-09-16 23:59:59 JST"]; 
NSLog(@"%@", capturedStartDate); 

Ma non funziona. Il suo dare un valore nullo. Si prega di aiutare ..

risposta

31

Quando si utilizza il tempo di 24 ore, l'ora specificatore deve essere la S maiuscola come questo:

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"]; 

Controllare qui per i prescrittori corrette: http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns

Tuttavia, è necessario impostare l'impostazione internazionale per la data formattatore:

// Set the locale as needed in the formatter (this example uses Japanese) 
[dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"ja_JP"]]; 

codice di lavoro completa:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"]; 
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"ja_JP"]]; 
NSDate *capturedStartDate = [dateFormatter dateFromString: @"2012-09-16 23:59:59 JST"]; 
NSLog(@"Captured Date %@", [capturedStartDate description]); 

uscite (in GMT):

Captured Date 2012-09-16 14:59:59 +0000 
+0

Hey @danielbeard, come u detto verrà visualizzato il tempo GMT, che mostrerà differenza di tempo di 9 ore dopo la data esatta. Come ottenere la data esatta dalla stringa .. ?? .. – NiKKi

+0

Le date non hanno fusi orari, ma è possibile ottenere una rappresentazione di stringa in un fuso orario con 'stringFromDate' con NSDateFormatter impostato sopra. – danielbeard

+0

Vedi qui per maggiori dettagli http://stackoverflow.com/questions/1862905/nsdate-convert-date-to-gmt – danielbeard

1
NSString *dateString = @"01-02-2010"; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 

// this is imporant - we set our input date format to match our input string 
// if format doesn't match you'll get nil from your string, so be careful 

[dateFormatter setDateFormat:@"dd-MM-yyyy"]; 
NSDate *dateFromString = [[NSDate alloc] init]; 
// end 
dateFromString = [dateFormatter dateFromString:dateString]; 
[dateFormatter release]; 
6
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"]; 
NSDate *capturedStartDate = [dateFormatter dateFromString: @"2012-09-16 23:59:59 GMT-08:00"]; 
NSLog(@"%@", capturedStartDate); 
+1

Questo potrebbe essere utile a qualcuno un giorno: Formato timestamp Keen.io '[formatter setDateFormat: @" yyyy -MM-dd'T'HH: mm: ss.SSS'Z '"];' Non ho bisogno di impostare le impostazioni internazionali. –

+0

La risposta mi è stata utile oggi;) –