简体   繁体   English

NSDateFormatter dateFromString错误的结果?

[英]NSDateFormatter dateFromString wrong result?

I'm trying to get an NSDate object from an NSString . 我正在尝试从NSString获取NSDate对象。 The problem is that, I'm losing 1 day in the process. 问题是,我在此过程中losing 1天。

This is the NSString : 2015-08-01 , and here is the code: 这是NSString2015-08-01 ,这是代码:

    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd"];
    NSDate *result = [df dateFromString:dateString];

The result turns out to be 2015-07-31 21:00:00 +0000 . result2015-07-31 21:00:00 +0000

How so? 怎么会这样? I don't understand. 我不明白 Besides, where did the 21:00:00 come from? 此外, 21:00:00从何而来? I'm getting this same result regardless of running the code on a real device or simulator. 无论在真实设备或模拟器上运行代码,我都得到相同的结果。

Any idea why ? 知道为什么吗? I'm suspecting a timezone issue. 我怀疑是timezone问题。 However, I'm getting the dateString in UTC format, and I'm not altering it. 但是,我以UTC格式获取了dateString ,并且没有对其进行更改。 Thoughts? 有什么想法吗?

检查时区。

[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];

Setting time zone will do the trick 设置时区可以解决问题

NSString *dateString = @"2015-08-01";
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    [df setDateFormat:@"yyyy-MM-dd"];
    NSDate *result = [df dateFromString:dateString];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM