Using DateFormatter with TimeZone to format dates in Swift

12.8k views Asked by At

How can I parse a date that has only date information (without time), like 2018-07-24

Im trying with

let dateFormatter = DateFormatter()
dateFormat.dateFormat = "yyyy-MM-dd"
dateFormatter.dateFormat = dateFormat
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")

dateFormatter.date(from: "2018-07-24")

prints day 23

It looks like it uses 00:00:00 as default time and then transform it into UTC results into the day before...

How can I change that?

1

There are 1 answers

0
Dmitry On

Seems that you set time zone for formatter to UTC but then try to get the day in your local time zone.

If you use this code - you will see the 24-th day

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")

let date = dateFormatter.date(from: "2018-07-24")

print(dateFormatter.string(from: date!)) // prints "2018-07-24"

But if you use "Calendar" to get the day component from the date you will get the day with your timeZone offset.

So for example in my time zone I see the 24th day (GMT+02) using this code

var calendar = Calendar.current
let day = calendar.component(.day, from: date!)
print(day) // prints 24

But if I set the time zone for calendar somewhere in USA I see the 23rd day

var calendar = Calendar.current
calendar.timeZone = TimeZone.init(abbreviation: "MDT")!
let day = calendar.component(.day, from: date!)
print(day) // prints 23

So the calendar uses your local time zone to get the component from date

So if you need to get the day component from date use the same time zone you used to parse the date from string.

var calendar = Calendar.current
calendar.timeZone = TimeZone(abbreviation: "UTC")!
let day = calendar.component(.day, from: date!)
print(day) // prints 24