I am using these lines of code to convert Date and time, to the current time zone:
let calendar = Calendar(identifier: .gregorian)
let currentDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss:Z"
dateFormatter.timeZone = calendar.timeZone
dateFormatter.string(from:currentDate)
print(dateFormatter.string(from: currentDate))
The print
output gives me:
2019-11-19 17:22:55:+0100
I am going to store the date in Realm, so how can I convert this back to a Date()
?
Edit; I tried converting it, but it doesn't work:
let calendar = Calendar(identifier: .gregorian)
let currentDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss:Z"
dateFormatter.timeZone = calendar.timeZone
let dateString = dateFormatter.string(from:currentDate)
let finalDate = dateFormatter.date(from: dateString)
print(dateString) -> Gives me output: 2019-11-19 18:09:05:+0100 - This is the correct time!
print(finalDate!) -> Gives me output: 2019-11-19 17:09:05 +0000
So the finalDate
should store the current time as a Date()
, but it doesn't get the correct time.