【问题标题】:NSDatePicker setDate doesn't work as expectedNSDatePicker setDate 没有按预期工作
【发布时间】:2020-04-16 05:00:14
【问题描述】:

我正在尝试根据我以毫秒为单位的某个偏移量在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 分钟是从哪里来的。

【问题讨论】:

  • setDate:animated: 是UIDatePicker 的一个方法。

标签: objective-c nsdate nscalendar nsdatecomponents nsdatepicker


【解决方案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];
}

【讨论】:

    猜你喜欢
    • 2021-10-19
    • 2020-03-18
    • 2012-06-14
    • 2014-11-15
    • 1970-01-01
    • 2012-07-02
    • 2011-09-07
    • 2013-03-03
    • 2015-05-18
    相关资源
    最近更新 更多