-
-
Save leandropjp/beca131918faa838b6d0a8c3e2accea2 to your computer and use it in GitHub Desktop.
Fast implementation for ISO8601 date formatter. Around 30 times faster than using (cached) DateFormatter
This file contains hidden or 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