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

SOLVED: Formatting a string as a date and ignoring text at the end?

Forums > SwiftUI

The JSON file I am working with has dates like this:

"date": "Sat Aug 20 2022 12:30:00 GMT+0100 (British Summer Time)"

I have been looking at this but unsure whether there is a way for Swift to ignore the (British Summer Time) bit?

https://www.hackingwithswift.com/example-code/system/how-to-convert-dates-and-times-to-a-string-using-dateformatter

Is it a case of needing to trim the text first with regex before trying to parse the string as a date?

1      

This part is incorrect: GMT+0100. It should be GMT+01:00 or GMT+1:00 per the Unicode standard for localized GMT format. You can correct that however you like and then the below code should work.

Alternatively (and perhaps easier), you could change the GMT part to UTC in which case the basic ISO8601 time zone format UTC+0100 will work.

import Foundation

struct TestStruct: Decodable {
    let name: String
    let activity: String
    let date: Date
}

let rawJSON = """
[
    {
        "name": "Charlotte Grote",
        "activity": "Solving",
        "date": "Sat Aug 20 2022 12:30:00 GMT+01:00 (British Summer Time)"
    },
    {
        "name": "Shauna Wickle",
        "activity": "Baking",
        "date": "Sat Aug 20 2022 12:30:00 UTC+0100 (British Summer Time)"
    }
]
""".data(using: .utf8)!

let fmt: DateFormatter = {
    let fmt = DateFormatter()
    fmt.dateFormat = "E MMM dd yyyy HH:mm:ss ZZZZ '('zzzz')'"
    fmt.locale = Locale(identifier: "en_US_POSIX")
    return fmt
}()

do {
    let decoder = JSONDecoder()
    decoder.dateDecodingStrategy = .formatted(fmt)
    let test = try decoder.decode([TestStruct].self, from: rawJSON)
    test.forEach {
        print("\($0.name) - \($0.activity) at \($0.date)")
    }
} catch {
    print(error)
}

Outputs:

Charlotte Grote - Solving at 2022-08-20 11:30:00 +0000
Shauna Wickle - Baking at 2022-08-20 11:30:00 +0000

1      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.