我正在努力:

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时间,我如何才能实现这一点?

谢谢

推荐答案

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

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

double secsUtc1970 = [[NSDate date]timeIntervalSince1970];

将日期格式化程序设置为输出本地时间:

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

Available NSTimeZone names

NSDate对象始终使用UTC作为时间参考,但日期的字符串表示形式不一定基于UTC时区.

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

在最初的问题中,最后一个词"时区"并不完美.

Objective-c相关问答推荐

CLLocationManager startUpdatingLocation 未调用 locationManager:didUpdateLocations: 或 locationManager:didFailWithError:

uipageviewcontroller 类在设置多个视图控制器时崩溃

Objective C中的简单字符串连接

如何更改 UIButton 的突出显示 colored颜色 ?

将未知数量的行添加到静态单元UITableView

pathForResource 返回 null

如何连续关闭 2 个模态视图控制器?

UIDatePicker,根据今天的日期设置最大和最小日期

反编译 Objective-C 库

Objective-C 中的 const 与静态 NSStrings

iOS 在设备旋转时更改自动布局约束

iOS 5:对 UIAppearance 感到好奇

WKWebView 判断 JavaScript 返回值

如何将@selector 作为参数传递?

从 UITabBarController 在当前上下文中呈现模态视图控制器后出现黑屏

如何检测 NSString 是否为空?

UIView: opaque vs. alpha vs. opacity

如何判断 NSString 的最后一个字符

如何在 Objective-c 中将数组声明为常量?

如何在对象内使用 objc_setAssociatedObject/objc_getAssociatedObject?