我正在尝试根据我以毫秒为单位的某个偏移量来设置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] = 17
po [components minute] = 8
po [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];
}