Forked from Pash237/ISO8601DateFormatter.swift
Created
August 30, 2023 17:14
Fast implementation for ISO8601 date formatter. Around 30 times faster than using (cached) DateFormatter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ISO8601DateFormatter { | |
private static var cachedCalendar: Calendar = { | |
var calendar = Calendar(identifier: .gregorian) | |
calendar.timeZone = TimeZone.gmt | |
return calendar | |
}() | |
static func format(_ date: Date) -> String { | |
let components = cachedCalendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date) | |
return withVaList([components.year ?? 1970, | |
components.month ?? 1, | |
components.day ?? 1, | |
components.hour ?? 0, | |
components.minute ?? 0, | |
components.second ?? 0], { pointer in | |
let chars = UnsafeMutablePointer<CChar>.allocate(capacity: 21) | |
vsnprintf(chars, 21, "%d-%02d-%02dT%02d:%02d:%02dZ", pointer) | |
return String(cString: chars) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment