2012-03-17 37 views
1

我想獲得當前時間,但我收到了GMT。我添加了語言環境,但它沒有幫助我。我使用iPod touch。哪裏不對?我想獲得當前時間,但我收到了GMT。哪裏不對?

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; 
    NSLocale *locale =[NSLocale currentLocale]; 
    [dateFormatter setLocale:locale]; 
    dateFormatter.dateFormat [email protected]"yyyy-MM-dd HH:mm:ss ZZZ"; 
    NSDate *date = [dateFormatter dateFromString:[[NSDate date] description]]; 

更新:我使用NSDateFormatter,因爲我需要證明

2012-03-17 12:20:33 

代替

2012-03-17 12:20:33 +0000 

回答

4

我成立了很好的解決方案。

NSCalendar * calendar = [NSCalendar currentCalendar]; 
NSDateComponents * components = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSSecondCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit 
              fromDate:[NSDate date]]; 
NSString * stringDate = [NSString stringWithFormat:@"%d-%d-%d %d:%d:%d", components.year, components.month, components.day, components.hour, components.minute, components.second]; 

另一種解決方案

NSDate *date = [NSDate date]; 
NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
NSTimeZone *zone = [NSTimeZone localTimeZone]; 
[formatter setTimeZone:zone]; 
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 

NSLog(@"Date %@",[formatter stringFromDate:date]); 
1

奇怪的是你爲什麼要在這裏經歷一個dateformatter? NSDate *date = [NSDate date];會給你一個有當前時間的日期。

+0

[NSDate的日期]給我唯一的GMT時間,但我需要一個本地時間。 – Voloda2 2012-03-17 12:18:33

+0

是的,但是如果沒有格式化程序,您無法可靠地提取該信息。我沒有看到其界面中的任何getTimeOfDay函數。 – borrrden 2012-03-17 12:21:44

3

好了,你也可以

NSTimeZone* local = [NSTimeZone localTimeZone]; 
NSInteger secondsOffset = [localTimeZone secondsFromGMTForDate:[NSDate date]]; 

然後,你可以將其添加到您現有的日期。

相關問題