簡體   English   中英

NSDatePicker setDate 沒有按預期工作

[英]NSDatePicker setDate doesn't work as expected

我正在嘗試根據以毫秒為單位的某個偏移量在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];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM