NSDatePicker setDate 未按预期工作



我正在尝试根据以毫秒为单位的某个偏移量在NSDatePicker上设置时间。当我设置时间时,我看到的值是关闭的,我无法弄清楚原因。 这是我用来设置选取器的代码:

- (void)setDatePicker{
int targetmillisondsFromMidnight = [self.schedule.targetHour intValue]; //Value is: 61680000 milliseconds whis is equal to 17:08 UTC (or 19:08 in my local time);
NSDate* todayMidnight = [NSCalendar.currentCalendar startOfDayForDate:[NSDate new]];
NSTimeZone* timezone = [NSTimeZone localTimeZone]; //Value is: Local Time Zone (Asia/Jerusalem (GMT‎+2‎) offset 7200)
NSInteger seconds = [timezone secondsFromGMT]; //Value is: 7200
todayMidnight = [todayMidnight dateByAddingTimeInterval:seconds]; // Value is: 2019-12-25 00:00:00 UTC
NSDate* scheduleDate = [NSDate dateWithTimeInterval:targetmillisondsFromMidnight/1000 sinceDate:todayMidnight]; //Value is: 2019-12-25 17:08:00 UTC
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:scheduleDate];
[self.datePicker setDate:[calendar dateFromComponents:components] animated:YES];
} 

我在函数的最后一个命令处以断点停止,并打印一些值,我得到的输出是:po [components hour] = 17po [components minute] = 8po [calendar dateFromComponents:components] = 001-01-01 17:08:00 +0000

因此,据我了解,日期定为17:08。 我希望在时间选择器上看到的是 19:08,但我看到的是 19:28。我不知道这20分钟是从哪里来的。

试试这段代码。日期选取器在设置时间时使用当前时区,并根据传递的日期 (001-01-01 17:08:00 +0000( 使用 UTC 偏移量,并在此时间点在时区数据库中查找偏移量。因为当时(零年(没有时区,所以在tz数据库中找不到时区,所以时区偏移量是根据平均太阳时计算的,所以你得到了你所在地区的偏移量2:20(大约(。

- (void)setDatePicker {
int targetmillisondsFromMidnight = 61680000; //Value is: 61680000 milliseconds whis is equal to 17:08 UTC (or 19:08 in my local time);
NSCalendar *calendar = NSCalendar.currentCalendar;
NSTimeZone* timezone = [NSTimeZone timeZoneWithName:@"Asia/Jerusalem"]; //Value is: Local Time Zone (Asia/Jerusalem (GMT‎+2‎) offset 7200)
calendar.timeZone = timezone;
NSDate* todayMidnight = [calendar startOfDayForDate:[NSDate new]];
NSInteger seconds = [timezone secondsFromGMT]; //Value is: 7200
todayMidnight = [todayMidnight dateByAddingTimeInterval:seconds]; // Value is: 2019-12-25 00:00:00 UTC
NSDate* scheduleDate = [NSDate dateWithTimeInterval:targetmillisondsFromMidnight/1000 sinceDate:todayMidnight]; //Value is: 2019-12-25 17:08:00 UTC
NSDate *date = [scheduleDate dateByAddingTimeInterval:seconds];
self.datePicker.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
[self.datePicker setDate:date animated:YES];
}

相关内容

  • 没有找到相关文章

最新更新