【发布时间】:2014-06-28 07:56:32
【问题描述】:
为什么以下标记的断言会失败?我只是在中欧的一台主机上运行这个单元测试。因此NSCalendar.currentCalendar.timeZone 是 CEST,即 GMT+0200。 NSDateComponents 返回这个时区,但它的其他值(例如年份等)显然与 GMT 相关。如何获取与 CEST 相关的值?
- (void)test {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mmZZZ";
dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"CEST"];
XCTAssertEqual(2 * 60 * 60, dateFormatter.timeZone.secondsFromGMT, @"");
NSDate *time = [dateFormatter dateFromString:@"2014-01-01T00:00+0200"]; // midnight on a Wednesday
NSCalendar *calendar = NSCalendar.currentCalendar; // i.e. CEST
XCTAssertEqual(2 * 60 * 60, calendar.timeZone.secondsFromGMT, @"");
NSDateComponents *components = [calendar components: NSYearCalendarUnit |
NSMonthCalendarUnit |
NSDayCalendarUnit |
NSWeekdayCalendarUnit |
NSHourCalendarUnit |
NSMinuteCalendarUnit |
NSTimeZoneCalendarUnit
fromDate:time];
XCTAssertEqual(components.year, 2014, @""); // fails with 2013
XCTAssertEqual(components.month, 1, @""); // fails with 12
XCTAssertEqual(components.day, 1, @""); // fails with 31
XCTAssertEqual(components.weekday, 4, @""); // fails with 3 (Tuesday)
XCTAssertEqual(components.hour, 0, @""); // fails with 23
XCTAssertEqual(components.minute, 0, @""); // succeeds
XCTAssertEqual(components.timeZone.secondsFromGMT, 2 * 60 * 60, @""); // succeeds (CEST)
}
【问题讨论】:
标签: ios objective-c nsdateformatter nscalendar nstimezone