DateFormatter bug

Hi, all.

I have found a weird result of DateFormatter.
Check out the code below.

let formatter = DateFormatter()

formatter.dateFormat = "yyyyMMdd"
formatter.date(from: "20220101") // 2022. 01. 01
formatter.date(from: "") // 2000. 01. 01
formatter.date(from: " ") // nil

I thnk passing empty string to DateFormatter should return nil like " ", but instead It returns the first day of 2000.

It it a bug or not?

Cheers!

Dong hyun Hwang

1 Like

It it a bug or not?

Regardless of this empty string issue, I want to highlight another couple of gotchas with DateFormatter:

  • Setting a fixed date format without also pinning the locale to en_US_POSIX will result in obscure bugs that likely only show up once you’ve deployed your app. See QA1480 NSDateFormatter and Internet Dates for more background on this.

  • Parsing dates without times is another source of bugs that only show up in the field. See my Parsing Dates Without Times post on DevForums.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

8 Likes

In my opinion it's a bug: passing an empty string to DateFormatter should not return an unexpected random date; filed as Feedback FB14744080, hopefully to at least have a note added to the documentation if this behavior is by design.

1 Like