【发布时间】:2020-04-14 22:20:24
【问题描述】:
我正在尝试在时间选择器上设置时间值,问题是由于时区问题导致时间混乱。这是我使用的代码 sn-p:
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] 而不是像scheduleDate 那样得到16 时,我得到18。
我怎样才能解决这个问题?
我尝试将时区更改为localTimeZone 和timeZoneWithAbbreviation:@"GMT",但似乎没有任何效果。
【问题讨论】:
标签: objective-c nsdate nscalendar nsdatecomponents nsdatepicker