Convert GMT NSDate to device's current Time Zone

前端 未结 6 1331
小蘑菇
小蘑菇 2020-12-08 05:30

I\'m using Parse.com to store some values:

\"enter

These are GMT values. How d

6条回答
  •  醉梦人生
    2020-12-08 06:03

    Creating an Xcode test case like the following may help us remember the rules "forever":

    - (void)test2015_05_23_07_07_07_Toronto {
        NSString *utcDateString = @"2015_05_23 12:07:07";
        NSDateFormatter *dateFormatter = [NSDateFormatter new];
        dateFormatter.dateFormat = @"yyyy_MM_dd HH:mm:ss";
    
        dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
        NSDate *date2015_05_23_12_07_07_UTC = [dateFormatter dateFromString:utcDateString];
    
        XCTAssertTrue([date2015_05_23_12_07_07_UTC.description isEqualToString:@"2015-05-23 12:07:07 +0000"]);
    
        dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"EST"];
        NSString *torontoDateString = [dateFormatter stringFromDate:date2015_05_23_12_07_07_UTC];
        XCTAssertTrue([torontoDateString isEqualToString:@"2015_05_23 07:07:07"]);
    
        // change format to add ZZZ
        dateFormatter.dateFormat = @"yyyy_MM_dd HH:mm:ss ZZZ";
        torontoDateString = [dateFormatter stringFromDate:date2015_05_23_12_07_07_UTC];
        XCTAssertTrue([torontoDateString isEqualToString:@"2015_05_23 07:07:07 -0500"]);
    
        XCTAssertEqual(1432382827, [date2015_05_23_12_07_07_UTC timeIntervalSince1970]);
    
        NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
        calendar.timeZone = [NSTimeZone timeZoneWithName:@"EST"];
        NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:date2015_05_23_12_07_07_UTC];
        XCTAssertEqual(2015, components.year);
        XCTAssertEqual(5, components.month);
        XCTAssertEqual(23, components.day);
        XCTAssertEqual(7, components.hour);
        XCTAssertEqual(7, components.minute);
        XCTAssertEqual(7, components.second);
    }
    

提交回复
热议问题