【问题标题】:Make NSDateFormatter emit the string "UTC" instead of the string "GMT"?让 NSDateFormatter 发出字符串“UTC”而不是字符串“GMT”?
【发布时间】:2019-06-17 22:36:56
【问题描述】:

我有以下 Objective-C 代码,它试图用 UTC 的当前日期/时间生成一个字符串:

NSDate *currentDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *utc = [NSTimeZone timeZoneWithName:@"UTC"];
[dateFormatter setTimeZone:utc];
[dateFormatter setDateFormat:@"YYYY-MM-dd--HH-mm-ss zzz"];
NSString *utcDateString = [dateFormatter stringFromDate:currentDate];

这段代码几乎生成了我想要的。我系统上utcDateString 的结果值为:

2019-06-17--22-28-13 GMT

但是,我想要的输出包括字符串“UTC”,不是“GMT”,如:

2019-06-17--22-28-13 UTC

有没有办法让NSDateFormatter 为日期格式的zzz 部分发出字符串“UTC”?我不希望不得不将“zzz”从我的日期格式字符串中删除,然后手动将“UTC”附加到生成的日期字符串上。

【问题讨论】:

    标签: objective-c nsdateformatter date-formatting


    【解决方案1】:

    没有返回UTC的日期格式说明符。

    由于您正在为格式化程序硬编码 UTC 时区,因此只需将字符串 UTC 硬编码为日期格式。

    另请注意,您需要yyyy,而不是YYYY

    [dateFormatter setDateFormat:@"yyyy-MM-dd--HH-mm-ss 'UTC'"];
    

    如果您需要处理其他时区并希望 GMT 显示为 UTC,然后使用 zzz(就像您已经使用的那样)并在结果上使用字符串替换将 GMT 转换为 UTC

    要考虑的另一个可能的想法是使用一定数量的X 作为时区说明符。这会将时区偏移量作为数字给出,但如果时区偏移量为 0,则结​​果为 Z(对于 Zulu)。

    【讨论】:

      猜你喜欢
      • 2021-04-21
      • 1970-01-01
      • 1970-01-01
      • 2011-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多