0

I try to format my UTC date but the result seems very wrong

DateFormatter:

    let df = DateFormatter()
    df.calendar = Calendar(identifier: .iso8601)
    df.dateFormat = "MMMM dd YYYY hh mm"
    df.locale = Locale(identifier: "en_US_POSIX")
    df.timeZone = TimeZone(identifier: "UTC")

Example 1

Date 1:

po dateStart
▿ 2018-12-31 00:00:00 +0000
- timeIntervalSinceReferenceDate : 567907200.0

Giving:

po df.string(from: dateStart)
"December 31 2019 12 00"

Example 2

Date 2:

po dateEnd
▿ 2021-01-03 23:59:59 +0000
- timeIntervalSinceReferenceDate : 631411199.0

Giving:

po df.string(from: dateEnd)
"January 03 2020 11 59"

Why does this happen and how can I get the correct Date (Year)?

Xavjer
  • 8,838
  • 2
  • 22
  • 42
  • `YYYY` vs `yyyy`? Also, you want `hh`, not `HH`? – Larme Jul 01 '19 at 10:32
  • I am just showing hh to show that the hour is also completely wrong. And the year is getting changed which is not correct (2018 gets formatted to 2019 and 2021 gets to 2020). I don't care about the hour (As I will only display Month and Year), but it's probably from the same issue – Xavjer Jul 01 '19 at 10:36
  • DateFormat are case sensitive. Look at the doc: http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns – Larme Jul 01 '19 at 10:40
  • @Xavjer Maybe this helps you https://stackoverflow.com/a/52477989/10150796 – Nikunj Kumbhani Jul 01 '19 at 10:47

1 Answers1

0

You should use "MMMM dd yyyy hh mm" instead of "MMMM dd YYYY hh mm" rest of seems ok to me.

Anupam Mishra
  • 3,408
  • 5
  • 35
  • 63
  • Can you explain the difference between yyyy and YYYY just so I understand why this happens – Xavjer Jul 01 '19 at 11:05
  • When using a date format string using the correct format is important. @"YYYY" is week-based calendar year. @"yyyy" is ordinary calendar year. https://stackoverflow.com/questions/15133549/difference-between-yyyy-and-yyyy-in-nsdateformatter/15133656 – Anupam Mishra Jul 01 '19 at 11:13