Search code examples
swiftxcodeuidatepicker

UIDatePicker not showing expected time


I'm very new to Swift and XCode. When choosing the time in the UIDatePicker, the time always seems to be 17 hours off. I can't find anything in the Apple Documentation explaining why this would happen.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var timePicker: UIDatePicker!

    @IBAction func startButton(_ sender: UIButton) {
        print(timePicker.date)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

}

Solution

  • As mentioned in the comment by @PJayRushton, you get a UTC date printed.

    In order to get your local timezone, you can modify your printing code to something like:

    import UIKit
    
    class ViewController: UIViewController {
    
        @IBOutlet weak var timePicker: UIDatePicker!
    
        @IBAction func startButton(_ sender: UIButton) {
            let dateFormatter = DateFormatter()
            dateFormatter.timeZone = TimeZone.current
            dateFormatter.dateFormat = "HH:mm" // or whatever other format you want
            print(dateFormatter.string(from: timePicker!.date))
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.
        }
    }