Objective-C,如何以UTC时区获取当前日期? [英] Objective-C, How can I get the current date in UTC timezone?

查看:199
本文介绍了Objective-C,如何以UTC时区获取当前日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试:

NSDate *currentDateInLocal = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:SS.SSS'Z'"];
NSString *currentLocalDateAsStr = [dateFormatter stringFromDate:currentDateInLocal];

NSDateFormatter * dateFormatter2 = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
[dateFormatter2 setTimeZone:timeZone];
[dateFormatter2 setDateFormat:@"yyyy-MM-dd'T'HH:mm:SS.SSS'Z'"];
NSDate *currentDateInUTC = [dateFormatter2 dateFromString:currentLocalDateAsStr];

但它仍然不代表当前的UTC时间,我该如何实现?

but It's still does not represent the current UTC time, how can I achieve this?

谢谢

推荐答案

NSDate *currentDate = [[NSDate alloc] init];

现在是UTC,(至少在使用下面的方法之后)

要将此时间存储为UTC(自参考日期1970起),请使用

Now it is in UTC, (at least after using the method below)
To store this time as UTC (since refernce date 1970) use

double secsUtc1970 = [[NSDate date]timeIntervalSince1970];

设置日期格式化程序输出当地时间:

Set Date formatter to output local time:

NSTimeZone *timeZone = [NSTimeZone defaultTimeZone];
// or Timezone with specific name like
// [NSTimeZone timeZoneWithName:@"Europe/Riga"] (see link below)
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSString *localDateString = [dateFormatter stringFromDate:currentDate];

可用的NSTimeZone名称

A NSDate 对象始终使用UTC作为时间参考,但字符串表示为基于UTC时区,日期不是必需的。

A NSDate object always uses UTC as time reference, but the string representation of a date is not neccessarily based on UTC timezone.

请注意,UTC不是(仅)一个时区,它是一个系统如何测量地球上的时间,它是如何测量的是协调的(UTC中的C代表协调)。

NSDate与UTC时间1.1.1970午夜的参考日期相关,尽管Apple稍微错误地将其描述为1.1.1970 GMT。

Please note that UTC is not (only) a timeZone, It is a system how time on earth is measured, how it is coordinated (The C in UTC stands for coordinated).
The NSDate is related to a reference Date of midnight 1.1.1970 UTC, altough slightly wrongly described by Apple as 1.1.1970 GMT.

在原始问题中,最后一个词timeZone并不完美。

In the original question the last word timeZone is not perfect.

这篇关于Objective-C,如何以UTC时区获取当前日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆