Reputation: 842
I have just migrated my app's code to Swift 3 and I am getting this really annoying issue with the DateFormatter(formerly NSDateFormatter) that I did not get with Swift 2 or earlier.
The issue is that I need to convert a string to a Date object and my code to do so is something like,
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let dateStr1 = "2017-02-22"
let date1 = dateFormatter.date(from: dateStr1)
Now this works fine and as expected in Xcode playgrounds but when I try to run it from my app, date1 returns 2017-02-21 13:00:00 +0000 i.e. a day in the past and I need date1 to be 2017-02-22 fyi, I am in Australia where I am doing this development.
I am getting the date string from my app's UI, and from the UI it's 2017-02-22 so I need to covert that string to a Date (or NSDate) object in Swift.
I have tried setting the TimeZone and Locale for the DateFormatter,
dateFormatter.timeZone = TimeZone(identifier: TimeZone.current.identifier)
dateFormatter.locale = Locale.init(identifier: Locale.current.identifier)
but still no luck?
I have also tried creating the Date from Calendar components like,
var dateComponents = DateComponents()
var day = "22"
var month = "02"
var year = "2017"
dateComponents.day = Int(day)!
dateComponents.year = Int(year)!
print(TimeZone.current)
dateComponents.timeZone = TimeZone.current
dateComponents.month = Int(month)!
let userCalendar = Calendar.current
let date1 = userCalendar.date(from: dateComponents)
But still not getting the right date i.e. getting 2017-02-21 instead of 2017-02-22 I have looked at some of the other SO questions like
How do you create a swift Date object
Converting date between timezones swift
amongst others. Any ideas of how I can achieve the result I want? this code was working completely fine prior to Swift.
Upvotes: 3
Views: 4123
Reputation: 2593
As maddy pointed out in the comments, Xcode is showing you the date in its "raw form" of Universal Timezone - UTZ - (also called Greenwich Meantime).
To get the date presented in another timezone you need to use the DateFormatter again.
So:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let dateStr1 = "2017-02-22"
let date1: Date = dateFormatter.date(from: dateStr1)!
print("\(date1)")
print("\(dateFormatter.string(from: date1))")
Gives you:
I'm running this code in Perth, Western Australia (i.e. UTZ+8) - therefore when I convert 22-Feb-2017 into a date it is stored as 21-Feb-2017 UTZ, but if I present it back with a DateFormatter from my locale I get midnight, 22-Feb-2017.
Upvotes: 2