Search code examples
swiftuidatepickernstimezone

convert Time Zone from NSDate


I have a UIDatePicker which is restricted to time only. And a localNotification is fired as soon this time reached. But if I print out the time it should fireOff it is always in the wrong Time Zone.

So I want to convert the Time Zone to the users local Time Zone before I pass it in the Local Notification function.

I tried it with this code but that obviously doesn't work

@IBOutlet weak var timePicker: UIDatePicker!

func convertTimeZone() ->NSDate {
        var date = timePicker.date
        var timeZone = NSTimeZone()
        date.TimeZone.localTimeZone
    }

Solution

  • var date = timePicker.date
    var timeZone = NSTimeZone.localTimeZone() //1
    
    let f = NSDateFormatter() 
    f.timeZone = timeZone //2
    f.dateFormat = "HH:mm:ss"
    
    let dateInUserTimezone = f.dateFromString(f.stringFromDate(date))! //3
    

    This uses the current user's timezone (1), then uses a date formatter (2) to change the date's timezone (3) by converting the date to a string then back to a date using the correct timezone.