UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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
    }

2      

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.

2      

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!

2      

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

2      

I can truly make the above code even simpler interior designer by omitting the requestLobbyInfo(from:) approach within the Player magnificence and, rather than checking if the contemporary player isn't the host and inquiring for data

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.