简体   繁体   中英

UIDatePicker showing the wrong time swift

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
    )
}

Hi , when i call self.datePicker.date return 3 hours back. How can i fix this problem i added self.datePicker.locale = NSLocale.currentLocale() but the problem not fixed. I can add more information if needed.

date picker uses its local time but it stores UTC time. It means your local time offset is -5h. You can do as follow to extract the right date and time from it:

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

println(chosenDate.localTime)

Props to Leo `

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM