NSDate set timezone in swift

If you always have the same time zone for the input string, you can create two date formatters to output the local time zone (or a specified one):

let timeFormatterGet = DateFormatter()
timeFormatterGet.dateFormat = "h:mm a"
timeFormatterGet.timeZone = TimeZone(abbreviation: "PST")

let timeFormatterPrint = DateFormatter()
timeFormatterPrint.dateFormat = "h:mm a"
// timeFormatterPrint.timeZone = TimeZone(abbreviation: "EST") // if you want to specify timezone for output, otherwise leave this line blank and it will default to devices timezone

if let date = timeFormatterGet.date(from: "3:30 PM") {
    print(timeFormatterPrint.string(from: date)). // "6:30 PM" if device in EST
} else {
   print("There was an error decoding the string")
}

The date format has to be assigned to the dateFormat property of the date formatter instead.

let date = NSDate.date()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let str = dateFormatter.stringFromDate(date)
println(str)

This prints the date using the default time zone on the device. Only if you want the output according to a different time zone then you would add for example

Swift 3.*

dateFormatter.timeZone = NSTimeZone(name: "UTC")

Swift 4.*

dateFormatter.timeZone = TimeZone(abbreviation: "UTC")

also refer link http://www.brianjcoleman.com/tutorial-nsdate-in-swift/


Swift 4.0

dateFormatter.timeZone = TimeZone(abbreviation: "UTC")

how can i return a NSDate in a predefined time zone?

You can't.

An instance of NSDate does not carry any information about timezone or calendar. It just simply identifies one point in universal time.

You can interpret this NSDate object in whatever calendar you want. Swift's string interpolation (the last line of your example code) uses an NSDateFormatter that uses UTC (that's the "+0000" in the output).

If you want the NSDate's value as a string in the current user's calendar you have to explicitly set up a date formatter for that.

Tags:

Nsdate

Swift