【问题标题】:UIDatePicker timeUIDatePicker 时间
【发布时间】:2015-09-09 12:44:00
【问题描述】:

我有一个 UIDatePicker 和一个按钮。当我按下按钮时,我想在日志中显示消息“为 x 设置提醒”,其中 x 是日期选择器显示的时间。

每次我按下按钮时,记录的时间都会比选择器显示的时间晚 3 小时(选择器显示的时间是我当前的时间)。我怀疑这与时区有关。我住在 GMT +2 时区(我猜是 +3,因为我们处于夏令时)。

您知道如何使记录的时间与显示的时间相同吗?

下面是我按下按钮时执行的方法。谢谢。

- (IBAction)addReminder:(id)sender {
    [self.datePicker setTimeZone:[NSTimeZone systemTimeZone]];
    NSLog(@"Setting a reminder for %@", self.datePicker.date);
}

【问题讨论】:

标签: ios objective-c uidatepicker


【解决方案1】:

NSDate 是某个时间点的简单表示,它对您的当地时间一无所知。当您记录它时(实际上是在发送description 时)消息,它使用GMT 来显示自己。

UIDatePicker 默认使用您的时区(请参阅https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIDatePicker_Class/#//apple_ref/occ/instp/UIDatePicker/timeZone)。

所以,它是这样工作的:

  • 您在 DatePicker 中选择了一些时间,但除非您指定时区,否则时间是没有意义的。
  • DatePicker 使用您的本地 (GMT+2) 时区并为其创建 NSDate
  • 您显示NSDate,由于它对时区一无所知,它只是将自己显示为GMT。

要显示您的日期,您应该使用NSDateFormatter。它有 Timezone 属性:https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/#//apple_ref/occ/instp/NSDateFormatter/timeZone

您也可以使用NSCalendar 及其组件。

您应该阅读本指南:https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html,因为除非您了解 Cocoa 的概念,否则日期、格式化程序和日历在 Cocoa 中并不是很清楚。

【讨论】:

    【解决方案2】:

    试试这个...

    NSDate *now = [[NSDate alloc] init];
    [self.datePicker setDate:now];
    [self.picker setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:2*60*60]]; // GMT+2 Your timeZone
    NSLog(@"Setting a reminder for %@", self.datePicker.date);
    

    【讨论】:

      猜你喜欢
      • 2011-08-29
      • 1970-01-01
      • 2011-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-11
      相关资源
      最近更新 更多