skip to Main Content

I’m having an issue where an attempt to turn a string into a date via a DateFromatter has produced nothing but ‘nil’ and I don’t know where I’m going wrong. The code is as simple as can be:

    let testDate = "2021"

    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX")
    formatter.dateFormat = "yyyy"

    formatter.timeZone = TimeZone(secondsFromGMT: 0)


    let date = formatter.date(from: testDate)

Note that this is much simpler than originally, the date I’m trying to format is actually:

"2021-05-01T01:00:00Z"

But I’ve stripped it right down to narrow down where the issue is.

As you can see from above, I’ve stripped down to a year, configured the DateFormatter with en_US_POSIX and used only the ‘yyyy’ as a format. This works in Playgrounds, but it doesn’t work in my Xcode simulator (Which is in the US locale) or my own physical iPhone (set to UK locale). That being said, I’ve no idea why the locale would matter because the string in question is just a year – it’m not even getting a wrong year, just nil.

I’m not sure where I’m going wrong.

2

Answers


  1. please use correct format like this for date string:

    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    

    instead of :

    formatter.dateFormat = "yyyy"
    

    each date string with specific formate like below code:

    let testDate = "2021"
        formatter.dateFormat = "yyyy"
    

    or

    let testDate = "2021-05-01T01:00:00Z"
    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    

    for more detail please see this link: https://stackoverflow.com/a/52297497/5140621

    Login or Signup to reply.
  2. Xcode Debugger has a bug as you can see in this post that it will show optional dates as nil even when parsing the date succeeds. If you print the optional date you will see the resulting date.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search