2012-08-25 78 views

回答

2

您可以使用帶MM-dd-yyyy的NSDateFormatter,然後使用NSTimeZone應用於格式器以調整本地時區。

此:

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

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

NSLog(@"%@", dateString); 

NSTimeZone *timeZone = [NSTimeZone localTimeZone]; 
[dateFormatter setTimeZone:timeZone]; 
NSLog(@"adjusted for timezone: %@", [dateFormatter stringFromDate:date]); 

輸出:

2012-08-26 08:30:53.741 Craplet[2585:707] 2012-08-26 12:30:53 +0000 
2012-08-26 08:30:53.742 Craplet[2585:707] 08-26-2012 08:30 
2012-08-26 08:30:53.743 Craplet[2585:707] adjusted for timezone: 08-26-2012 08:30 
+0

謝謝!這就像一個魅力。如何,我真正在尋找的是以某種方式獲得LOCAL dateFormat。最好在NSString中。你能幫助我嗎? –

+0

我更新瞭如何使用本地時區。我加了hh:mm只是爲了演示目的來顯示它是本地的。 – bryanmac

6

NSDateFormatter有一個方便的類方法:

[NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterNoStyle]; 

您可以指定NSDateFormatterNoStyle,.. ShortStyle,.. MediumStyle,或..LongStyle

相關問題