我正在尝试在时间选择器上设置时间值,问题是由于时区问题导致时间混乱。这是我使用的代码片段:
int targetmillisondsFromMidnight = [self.schedule.targetHour intValue]; // 59580000
NSDate* todayMidnight = [NSCalendar.currentCalendar startOfDayForDate:[NSDate new]]; //2019-12-23 00:00:00 UTC
NSTimeZone* timezone = [NSTimeZone defaultTimeZone];
NSInteger seconds = [timezone secondsFromGMT];
todayMidnight = [todayMidnight dateByAddingTimeInterval:seconds];
NSDate* scheduleDate = [NSDate dateWithTimeInterval:targetmillisondsFromMidnight/1000 sinceDate:todayMidnight]; //2019-12-23 16:33:00 UTC
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone defaultTimeZone]];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:scheduleDate];
[self.datePicker setTimeZone:[NSTimeZone defaultTimeZone]];
[self.datePicker setDate:[calendar dateFromComponents:components] animated:YES];
当我这样做po [components hour]
而不是得到 16 时,scheduleDate
我得到 18。我该如何解决这个问题?我试图将时区更改为localTimeZone
,timeZoneWithAbbreviation:@"GMT"
但似乎没有任何效果。