ios - 如何在iOS中获取当前本地时间

标签 ios nsdate nsdateformatter

我正在尝试从设备获取本地时间

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/

相关文章:

ios - ActionSheet 源 View BarButtonItem

iphone - UIView 上的圆角

objective-c - Http 日期到 NSDate

iphone - 使用sortedArrayUsingComparator对包含NSArray的NSMutableArray进行排序

iPhone 使用用户区域设置但以其他语言显示日期

ios - 快速从调用者到被调用者的回调函数

ios - 我可以自定义 UIReferenceLibraryViewController 的外观和 "Done"按钮吗?

字符串到 NSDate 的转换适用于英语,但不适用于俄语

objective-c - 使用 NSDate 的本地化日期(月和日)和时间

ios - 在 objective-c 的选定日期中使用 dateWithTimeInterval 添加 3 秒后获取无效时间