currentDateDateFormatter

currentDateDateFormatter

我有此代码来获取本地日期/时间。它可以工作,但是要获取我当前的日期/时间值而不是GMT时间似乎很漫长(10条语句)。

NSDate          *currentDateGMT = [NSDate date];
NSDateFormatter *currentDateDateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone      *currentDateTimeZoneGMT = [NSTimeZone timeZoneWithName:@"GMT"];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];

[currentDateDateFormatter setTimeZone: currentDateTimeZoneGMT];
[currentDateDateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
[currentDateDateFormatter setLocale:locale];

NSString *currentDateString = [currentDateDateFormatter stringFromDate:currentDateGMT];
NSDate *currentDateAdjusted = [currentDateDateFormatter dateFromString:currentDateString];

[currentDateDateFormatter release];


有人可以确认这是获得当前机器价值的最佳方法吗?

谢谢

最佳答案

NSDateFormatter将默认为用户时区,因此最简单的解决方案是

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//lower case h for hour will also default to the users
//12/24 hour clock preference
[formatter setDateFormat:@"yyyy-MM-dd hh:mm"];

NSString *currentDate = [formatter stringFromDate:[NSDate date]];

[formatter release];

08-18 09:07