0

我正在尝试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 分钟是从哪里来的。

4

1 回答 1

1

试试这个代码。日期选择器在设置时间当前时区时使用,并使用基于传递日期 (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];
}
于 2019-12-25T17:54:30.513 回答