Dates ยท SWIFT RECIPE

Parse an ISO 8601 date

Turn an internet timestamp into a Date.

main.swift
import Foundation
let formatter = ISO8601DateFormatter()
if let date = formatter.date(from: "2024-01-01T12:00:00Z") {
    print(Int(date.timeIntervalSince1970))
} else { print("Invalid timestamp") }

How it works

ISO8601DateFormatter handles internet timestamps with explicit offsets. Parsing returns an optional because invalid text cannot represent a valid date.

EXPECTED OUTPUT
1704110400

Keep in mind

Add .withFractionalSeconds to formatOptions when the source includes fractional seconds.

Read the Swift language reference