我正在尝试从设备获取本地时间
nsdate将返回UTC时间
当我与本地时区转换时,字符串将返回当前本地时间...
我再次尝试将字符串转换为本地日期,但它只会返回UTC时间
这是我的代码...如何在NSDate中获取本地时间...
NSDate *currentDate = [NSDate date];
NSLog(@"currentDate: %@", currentDate); // Result: currentDate: 2014-05-19 05:21:50 +0000
NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
[dateFormatter2 setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter2 setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
NSString *strDate = [dateFormatter2 stringFromDate:currentDate];
NSLog(@"strDate: %@", strDate); // Result: strDate: 2014/05/19 10:51:50
NSDate *newDate = [dateFormatter2 dateFromString:strDate];
NSLog(@"newDate: %@", newDate); // Result: newDate: 2014-05-19 05:21:50 +0000
谁能帮忙获取NSDate中的本地日期时间
最佳答案
试试这个:
NSDate* sourceDate = [NSDate date];
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];
关于ios - 如何在iOS中获取当前本地时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23730234/