Brosef Brosef - 11 months ago 49
iOS Question

day for Date() and Calendar.dateComponents don't match up

I'm trying to get the current date to print in a particular format (YYYYMMD) for AWS security credentials and I noticed that when I do

, the day is the 4th which is the correct value:

let date = Date()
print("\(date)") //2016-10-04 00:56:28 +0000

Now, I want to print the date in the format I desire so, but I keep getting the day value as the 3rd:

let calendar = Calendar.current
let date = Date()
let components = calendar.dateComponents([.day], from: date)
print("\(") //Optional(3)

S3 is expecting the date to be the 4th. How can I fix this?

Answer Source

It's because of time zone difference. date will return the UTC time and date but calendar will return the date and time based on your device's time zone. If you need the day number in UTC just set the time zone of the calendar object to UTC after you create it:

let calendar = Calendar.current
calendar.timeZone = TimeZone(abbreviation: "UTC")!

Now it will always match the value that is returned by Date()