2010-02-22 169 views
20

什麼是使用Objective-C獲取當前時間(HH:MM:SS)的最佳方式。我想我應該看NSDate & NSDateFormatter。我快速瀏覽了文檔,看起來比我預期的更復雜,所以我想我會在這裏檢查以確保我處於正確的軌道上。獲取當前系統時間?

加里

回答

47
NSDate * now = [NSDate date]; 
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init]; 
[outputFormatter setDateFormat:@"HH:mm:ss"]; 
NSString *newDateString = [outputFormatter stringFromDate:now]; 
NSLog(@"newDateString %@", newDateString); 
[outputFormatter release]; 
6

你,其實,在正確的軌道。使用

NSDate *date = [NSDate date]; 

獲得當前的日期和時間。使用NSDateFormatter進行格式化。請參閱this link瞭解如何使用日期和時間格式。

對於你的情況,你可以這樣做:

NSDate *date = [NSDate date]; 
NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
[formatter setDateFormat:@"%H:%M:%S"]; 
NSString *timeString = [formatter stringFromDate:date]; 
2
NSDateFormatter *DateFormatter=[[NSDateFormatter alloc] init]; 

[DateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"]; 
NSLog(@"%@",[DateFormatter stringFromDate:[NSDate date]]);