美文网首页iOS进阶指南iOS DeveloperiOS 开发
UIDatePicker 选取日期 差8个小时+0000

UIDatePicker 选取日期 差8个小时+0000

作者: GGRay | 来源:发表于2016-06-16 12:08 被阅读1847次
    获取日期后,发现与实际时间相差8个小时,除了正常的时区问题之外,还有可能是因为你DatePicker的使用方式不当.
    

    通常的时区间隔8小时解决办法:
    NSTimeZone *timeZone=[NSTimeZone systemTimeZone];
    NSInteger seconds=[timeZone secondsFromGMTForDate:date];
    NSDate *newDate=[date dateByAddingTimeInterval:seconds];
    NSString *newTimeStr=[formatter stringFromDate:newDate];

    但是如果你是由于取出来DatePicker造成这个现象,是因为你获取的dateString后面多了+0000 既英国时区:
    输出+0000的原因是
    _resultString=[NSString stringWithFormat:@"%@",_datePicker.date];

    此时的解决办法是:
    //去掉 +0000
    NSDate *select = [_datePicker date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    _resultString=[dateFormatter stringFromDate:select];
    //计算时差
    NSTimeZone *timeZone=[NSTimeZone systemTimeZone];
    NSInteger seconds=[timeZone secondsFromGMTForDate:date];
    NSDate *newDate=[date dateByAddingTimeInterval:seconds];
    NSString *newTimeStr=[formatter stringFromDate:newDate];
    就可以完美解决这个问题了.

    相关文章

      网友评论

        本文标题:UIDatePicker 选取日期 差8个小时+0000

        本文链接:https://www.haomeiwen.com/subject/hvymdttx.html