UIDatePicker显示错误的时间swift

时间:2016-04-05 13:25:27

标签: ios swift uidatepicker

func show(title: String, doneButtonTitle: String = "Done", cancelButtonTitle: String = "Cancel", defaultDate: NSDate = NSDate(), datePickerMode: UIDatePickerMode = .DateAndTime, callback: DatePickerCallback) {
    self.titleLabel.text = title
    self.doneButton.setTitle(doneButtonTitle, forState: .Normal)
    self.cancelButton.setTitle(cancelButtonTitle, forState: .Normal)
    self.datePickerMode = datePickerMode
    self.callback = callback
    self.defaultDate = defaultDate
    self.datePicker.datePickerMode = self.datePickerMode ?? .Date
    self.datePicker.date = self.defaultDate ?? NSDate()
    self.datePicker.locale = NSLocale.currentLocale()
    /* */
    UIApplication.sharedApplication().windows.first!.addSubview(self)
    UIApplication.sharedApplication().windows.first!.endEditing(true)

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "deviceOrientationDidChange:", name: UIDeviceOrientationDidChangeNotification, object: nil)

    /* Anim */
    UIView.animateWithDuration(
        0.2,
        delay: 0,
        options: UIViewAnimationOptions.CurveEaseInOut,
        animations: { () -> Void in
            self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
            self.dialogView!.layer.opacity = 1
            self.dialogView!.layer.transform = CATransform3DMakeScale(1, 1, 1)
        },
        completion: nil
    )
}

嗨,当我打电话给self.datePicker.date 3小时后回来。我怎么能解决这个问题,我添加了self.datePicker.locale = NSLocale.currentLocale(),但问题没有解决。如果需要,我可以添加更多信息。

1 个答案:

答案 0 :(得分:0)

日期选择器使用其本地时间但存储UTC时间。这意味着您当地的时间偏差为-5小时。您可以按照以下步骤从中提取正确的日期和时间:

extension NSDate {
    var localTime: String {
       return descriptionWithLocale(NSLocale.currentLocale())! 
    }
}

println(chosenDate.localTime)

支持Leo`