【问题标题】:Convert UTC time to system time getting null将 UTC 时间转换为系统时间为空
【发布时间】:2017-12-07 11:11:45
【问题描述】:
 NSString *strUTCTime=@"2017-07-06T10:00:00";

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
 dateFormatter.dateFormat = @"yyyy-MM-ddTHH:mm:ss";

 NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
 [dateFormatter setTimeZone:destinationTimeZone];

 NSDate *oldTime = [dateFormatter dateFromString:strUTCTime];

 NSString *estDateString = [dateFormatter stringFromDate:oldTime];
 NSLog(@"Local time is ===> %@",estDateString);

【问题讨论】:

  • 您需要自己调试,或者至少向我们展示一些有用的结果。例如oldTimenil,这就是为什么estDateString 无论如何都会为零。所以你的问题来自于获得oldTime。事实上,我删除了 timeZone 的东西来检查我是否可以获得 NSDate 而不是。它帮助我发现问题出在dateFormat,您需要“转义”T => dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss";
  • 是的,需要转义 T 谢谢。 =====> dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss";

标签: ios objective-c nsdate nsdateformatter


【解决方案1】:

以下是以下工作和测试代码。

NSString *strUTCTime=@"2017-07-06T10:00:00";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss";
[dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en-US"]];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];

NSDate *oldTime = [dateFormatter dateFromString:strUTCTime];

NSLog(@"UTC time is ===> %@",oldTime);

NSTimeZone* destinationTimeZone = [NSTimeZone localTimeZone];
[dateFormatter setTimeZone:destinationTimeZone];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";

NSString *estDateString = [dateFormatter stringFromDate:oldTime];
NSLog(@"Local time is ===> %@",estDateString);

如果有效,请告诉我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-27
    • 2021-09-05
    • 1970-01-01
    • 2017-04-27
    • 2013-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多