iOS UIDatePicker的日期和现在的日期早8小时

时间:2018-05-24 01:05:54

标签: ios swift timezone uidatepicker

有我的代码,我已经处理了时区,现在来自datepicker的时间是正确的,但是datepicker上显示的时间仍然是错误的,使用Date()获得的当前时间是也错了。

 @IBAction func dateChanged(_ datePicker: UIDatePicker) {
            let timeZone = NSTimeZone.system
            let interval = timeZone.secondsFromGMT(for: datePicker.date)

            let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .timeZone], from: datePicker.date.addingTimeInterval(TimeInterval(interval)))
            remindDate = Calendar.current.date(from: dateComponents)!

            print("+++++++++++++DatePicker: \(datePicker.date)++++++++++++++Date: \(remindDate)++++++++++++++Now: \(Date())+++++++++++++")

            updateDateDetial(remindDate)

        }

以下是print()

的结果
  

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 25 10:44:00 +0000 +++++++++++++++++++++++++++++++++++++++++++++++++++++++   0000 +++++++++++++

我从datepicker选择的时间是2018-05-25 10:44。现在的时间应该是2018-05-24 8:44:38。但是,该计划的时间仍然存在差距。

1 个答案:

答案 0 :(得分:1)

从GMT添加时间间隔偏移的代码是错误的。不要那样做。

您面临的问题是默认情况下日期以GMT(UTC)显示。您可以使用DateFormatter类方法localizedDate为您提供当前语言环境中的日期字符串。

let datePickerDateString = DateFormatter.localizedString(from: datePicker.date,
  dateStyle: .medium,
  timeStyle, .medium)
let remindDateString = DateFormatter.localizedString(from: remindDate,
  dateStyle: .medium,
  timeStyle, .medium)
let nowString = DateFormatter.localizedString(from: Date(),
  dateStyle: .medium,
  timeStyle, .medium)
print("+++++++++++++DatePicker: \(datePickerDateString)++++++++++++++Date: \(remindDateString)++++++++++++++Now: \(nowString)+++++++++++++")

我为Date类创建了一个简单的扩展,使这更容易做到:

extension Date {
    func localString(dateStyle: DateFormatter.Style = .medium, timeStyle: DateFormatter.Style = .medium) -> String {
        return DateFormatter.localizedString(from: self, dateStyle: dateStyle, timeStyle: timeStyle)
    }
}

将您的代码折叠为:

        print("+++++++++++++DatePicker: \(datePicker.date.localString())" + 
              "++++++++++++++Date: \(remindDate.localString())" + 
              "++++++++++++++Now: \(Date().localString())+++++++++++++")

修改

如果您将日期选择器的日期安装到代码可能如下所示的标签中(使用上面的Date扩展名)

myLabel.text = datePicker.date.localString()

(虽然请注意,当用户更改日期时,您应该将日期保存到实例变量中,而不是从日期选择器中获取它。在视图对象中保存模型数据是代码味道。)