WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

How to convert string into date

Forums > Swift

Hi!

I'm using Contentful to fetch my app's content. They return the date as ISO 8601 string. I know how to convert a string into a date with DateFormatter or ISO8601DateFormatter, but when I fetch a date from API I have nil.

String format example I need to convert:

2022-05-02T00:00+03:00

Func I use to do it:

    func dateFromString(string: String) -> Date {
        let dateFormatter = ISO8601DateFormatter()
        let date = dateFormatter.date(from: string) ?? Date.now
        print(dateFormatter.date(from: string)?.stringValue ?? "Empty")
        print("ISO TIME: " + string)
        return date
    }

Please tell what I'm doing wrong and how to fix it?

Thank you! Slava Ukraine!

P.S. I fixed it.

func dateFromString(string: String) -> Date {
        let dateFormatter = ISO8601DateFormatter()
        dateFormatter.formatOptions = [.withFullDate] // Added format options
        let date = dateFormatter.date(from: string) ?? Date.now
        print(dateFormatter.date(from: string)?.stringValue ?? "Empty")
        print("ISO TIME: " + string)
        return date
    }

   

Eugene is exploring ISO time. Good luck!

They return the date as ISO 8601 string.
I know how to convert a string into a date with DateFormatter or
ISO8601DateFormatter, but when I fetch a date from API I have nil.

First, nice job finding a fix and reporting back. This will help others who might ask the same question!

You might want to consider returning an optional Date instead of the current date. If your user provides a bogus ISO date, returning nil allows you to consider other options. You may even consider writing your function so it throws an error.

// Paste into Playgrounds.
// Consider returning an optional.
// You'll want to know if the user entered an isoString incorrectly
func dateFromISOString(_ isoString: String) -> Date? {
    let isoDateFormatter = ISO8601DateFormatter()
    isoDateFormatter.formatOptions = [.withFullDate]  // ignores time!
    return isoDateFormatter.date(from: isoString)  // returns nil, if isoString is malformed.
}

// Examine your test case. Notice the result ignores time.
// Notice too, date is adjusted for local time zone.
dateFromISOString("2022-05-02T00:00+03:00") // Notice this ignores time
dateFromISOString("2022-05-03")             // Notice this ignores time
dateFromISOString("2022-07-01T1:10:56Z")    // Different ISO format, ignores time
dateFromISOString("not_an_iso_date")        // Bogus input. Fail.

   

Additional observations:

@twoStraws notes in one of his videos that working with Dates is hard. Very hard.

I found a great resource, perhaps this will help you too?

See-> Working with Dates

In short, this video goes into great detail about parsing and formatting ISO dates and the tricky business of time zones.

Once you have a nice Date object, you might want to show this date to your user! However, users in England, US, Germany, and Spain all use different formats! This video has great hints how to avoid hard coding various formats and to rely on a user's locale to solve the display problem.

Added bonus! Besides this excellent video, Ben created a terrific web site allowing you to interactively test different Swift date formats. See the results as you change format options! Cool.

See-> NSDateFormatter.com

Please report back if this helps!

   

How are your getting the data. if you are using JSON decoder then it build in with

JSONDecoder().dateDecodingStrategy = .iso8601

this will return it as a Date

   

Hacking with Swift is sponsored by Emerge

SPONSORED Why are Swift reference types bad for app startup time, and what’s the performance cost of protocol conformances? That’s just a couple of the topics you can learn about on the Emerge blog — written by the app performance experts behind Emerge’s advanced app optimization and monitoring tools, based on their experience of working at companies like Apple, Airbnb, Snap, and Spotify.

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.