【问题标题】:How to get current local time in ios如何在ios中获取当前本地时间
【发布时间】:2014-07-06 23:16:41
【问题描述】:

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

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 中获取本地日期时间

【问题讨论】:

  • OP 声明:“当我使用本地时区转换时,字符串将返回当前本地时间”所以没有问题。

标签: ios nsdate nsdateformatter


【解决方案1】:

试试这个:

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];

【讨论】:

  • NSDate 值需要引用“2001 年 1 月 1 日,格林威治标准时间的第一个实例”,这是定义。其他任何东西都无法跨时区正常工作。
【解决方案2】:

时间总是以 UTC 格式保存在NSDate,不能更改。

可以获得本地时区的字符串表示,OP 已经做到了。

NSDate 的参考日期为“2001 年 1 月 1 日,格林威治标准时间”

【讨论】:

    猜你喜欢
    • 2018-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多