Search code examples
iosswiftdatedateformatter

Dateformatter Result


Here is my DateFormatter Code

 let formatter = DateFormatter()
 formatter.dateFormat = "MMM dd"
 let dateString = formatter.string(from: date)

Now:

po dateString 

gives the result "May 18"

po date gives the result 2021-05-17 18:30:00 +0000

This does not make sense to me - why is the Date May 17 2021 being converted to the String May 18?


Solution

  • A Date object records an instant in time anywhere on the planet.

    That instant in time will be on a different calendar day (day/month/year) depending on what time zone you are in.

    By default, date formatters work in the device's current time zone.

    When you log a Date using po date or print(date) the default description of a Date displays that date in UTC using the ISO 8601 date format. Depending on the user's time zone, the Date in UTC might be on a different calendar day than it is in the local time zone

    If you want to log a date in the user's local time zone, use po date.description(with: Locale.current) or po DateFormatter.localizedString(from: date, dateStyle: .medium, timeStyle: .medium)