Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting wrong date when converting string with timezone

Tags:

date

swift

In Swift Playground, I run this.

let string = "2019-01-14T00:00:00+08:00"
let utcTimezone = TimeZone(abbreviation: "UTC")!
let sgtTimezone = TimeZone(abbreviation: "SGT")!

let dfs = DateFormatter()
dfs.timeZone = sgtTimezone
dfs.locale = Locale(identifier: "en_sg")
dfs.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZ"
dfs.calendar = Calendar(identifier: Calendar.Identifier.iso8601)

let date = dfs.date(from: string)!

Why is date = Jan 13, 2019 at 11:00 PM and not the accurate Jan 14, 2019 at 00:00 AM ?

Tried changing the timezone to UTC but by default the result is UTC I am expecting Jan 14, 2019 at 00:00 AM.. or at least Jan 14

like image 269
Vina Avatar asked Oct 15 '25 19:10

Vina


1 Answers

// This lets us parse a date from the server using the RFC3339 format
let rfc3339DateFormatter = DateFormatter()
rfc3339DateFormatter.locale = Locale(identifier: "en_US_POSIX")
rfc3339DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
rfc3339DateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

// This string is just a human readable format. 
// The timezone at the end of this string does not mean your date 
// will magically contain this timezone. 
// It just tells the parser what timezone to use to convert this 
// string into a date which is basically just seconds since epoch.
let string = "2019-01-14T00:00:00+08:00"

// At this point the date object has no timezone
let shiftDate = rfc3339DateFormatter.date(from: string)!

// If you want to keep printing in SGT, you have to give the formatter an SGT timezone.
let printFormatter = DateFormatter()
printFormatter.dateStyle = .none
printFormatter.timeStyle = .full
printFormatter.timeZone = TimeZone(abbreviation: "SGT")!
let formattedDate = printFormatter.string(from: shiftDate)

You will notice that it prints 12am. There is nothing wrong with your code. You just misunderstand the Date object. Most people do.

Edit: I used the RFC formatter found in the Apple docs here. The result is the same if you use your formatter. And yes, as rmatty said, there are a few things wrong with your formatter (I stand corrected :))

like image 155
Jacob Avatar answered Oct 18 '25 14:10

Jacob