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

Converting a string to a date

Forums > Swift

Any idea why date is nor printed to the debug console? Dates are hard! :)

let isoDate = "2023-01-08T00:01:08.342782Z"

    let dateFormatter3 = DateFormatter()
    dateFormatter3.dateFormat = "yyyy-MM-dd'T'HH:mm:ssssssZ"
    if let date = dateFormatter3.date(from: isoDate) {
        print(date)
    }

2      

firstly this is not a ISO date (I think) this is the format for this 2022-12-14T04:30:00+05:30 and the use

import Foundation
let isoDate = "2022-12-14T04:30:00+05:30"
let dateFormatter = ISO8601DateFormatter()

if let date = dateFormatter.date(from: isoDate) { 
    print(date)
}

2      

2023-01-08T00:01:08.342782Z is a valid ISO8601 date time string, just one using milliseconds.

ISO8601DateFormatter can handle such a format like so:

import Foundation

let isoDate = "2023-01-08T00:01:08.342782Z"

let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
if let date = dateFormatter.date(from: isoDate) {
    print(date)
}

4      

Nice one. learn something everyday

2      

@roosterboy @flaneur7508 @NigelGee - wish you all a happy new year , and yes @roosterboy, thanks for this solution, something to keep bookmarked ..

2      

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!

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.