目标 C 将字符串转换为 UTC - 时间移动错误



>我从数据库中返回一个字符串,值是'04/27/2016 1:16pm'。 此值已采用 UTC。

现在我想将该字符串转换为 NSDATE,将其保留为 UTC。 当我尝试将字符串转换为日期时,时间实际上移动了 1 小时。

这就是我的做法

NSString *tuploadtime = [tempDictionary valueForKey:@"uploadTime"];
    //date conversions
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM-dd-yyyy HH:mm:ss a"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
    NSDate *duploadtime = [[NSDate alloc] init];
    duploadtime = [dateFormatter dateFromString:tuploadtime];
    NSLog(@"tuploadtime=%@, duploadtime=%@", tuploadtime, duploadtime);

结果将返回为 2016-04-27 12:16:01 UTC。结果是

2016-04-27 10:12:44.612 x[1558:48608] 上传时间=4/27/2016 2:10:33 PM, 上传时间=2016-04-27 12:10:33 +0000

基本上时间是向后移动 1 小时,但我想保持不变。希望我说得有道理

日期的Proper String Format是最重要的。

有一些方法可以HOURS格式,如下所示,但它们的差异。

kk:将在 (01-24) 小时内返回 24 格式的小时(看起来像 01、02..24)。

HH 将在 (00-23) 小时内返回 24 格式的小时(看起来像 00、01..23)。

hh将返回 12 格式的小时(看起来像 01、02..12)。

所以你应该像这样使用你的代码

NSString *tuploadtime = [tempDictionary valueForKey:@"uploadTime"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM-dd-yyyy hh:mm:ss a"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
NSDate *duploadtime = [[NSDate alloc] init];
duploadtime = [dateFormatter dateFromString:tuploadtime];
NSLog(@"tuploadtime=%@, duploadtime=%@", tuploadtime, duploadtime);

有关更多日期格式,请参阅此链接

日期格式字符串不一致:

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

HH表示使用 24 小时格式。但是,您也使用a来表示 AM/PM。 同时使用两者会混淆格式化程序并让您一一脱。你的意思是在这里使用hh

最新更新