TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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 RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.