2011-12-05 11 views
5

Il seguente dovrebbe darmi un oggetto NSDate di 9:30:Ottenere ora corrente su iPhone in un formato scelto

NSString *dateString = @"09-30"; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"hh-mm"]; 
NSDate *dateFromString = [[NSDate alloc] init]; 
dateFromString = [dateFormatter dateFromString:dateString]; 

Come faccio ad avere l'ora corrente nello stesso formato?

risposta

15
NSDate *currentTime = [NSDate date]; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"hh-mm"]; 
NSString *resultString = [dateFormatter stringFromDate: currentTime]; 
+1

NSString * Risultato = [dateFromatter stringFromDate: currentTime]; cambia dataFromatter a dataFormatter –

+0

thx per spotting typo – Denis

2
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"hh-mm"]; 
NSDate *currentDate = [NSDate date]; 
NSString *currentDateString = [dateFormatter stringFromDate:currentDate]; 
0
NSDate *currentDate =[NSDate date]; 
//Your formatter goes here. 
NSString *currentTime = [dateFormatter stringFromDate:currentDate]; 
1

NSDate alloc init creerà una data con l'ora corrente. Quindi, è possibile utilizzare NSDateFormatter stringFromDate per il formato e presentare quella data.

Questo:

NSDate *date = [[NSDate alloc] init]; 
NSLog(@"%@", date); 

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"hh-mm"]; 
NSString *dateString = [dateFormatter stringFromDate:date]; 

NSLog(@"%@", dateString); 

Uscite:

2011-12-05 07:20:02.994 Craplet[1706:707] 2011-12-05 12:20:02 +0000 
2011-12-05 07:20:02.995 Craplet[1706:707] 07-20 
1
NSDate *today = [[NSDate alloc] init]; 
NSLog(@"today is :%@", date); 

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"hh-mm:ss"]; 
NSString *timeString = [dateFormatter stringFromDate:today]; 

NSLog(@"%@", timeString); 
Problemi correlati