Skip to content

Instantly share code, notes, and snippets.

@EricShapiro
Created December 13, 2020 19:15
Show Gist options
  • Save EricShapiro/20684569d8953abd6c71a52773b66ff0 to your computer and use it in GitHub Desktop.
Save EricShapiro/20684569d8953abd6c71a52773b66ff0 to your computer and use it in GitHub Desktop.
extension DateFormatter {
/*
DateFormatters are notoriously slow to create, so it's best to share them.
However, they're not thread safe, so this returns one DateFormatter per thread.
*/
static var shared : DateFormatter {
let key = "com.relium.swift.DateFormatter"
if let f1 = Thread.current.threadDictionary[key] as? DateFormatter {
return f1
}
else {
let f2 = DateFormatter()
Thread.current.threadDictionary[key] = f2
return f2
}
}
static let using12hClockFormat : Bool = {
let formatter = DateFormatter()
formatter.locale = Locale.current
formatter.dateStyle = .none
formatter.timeStyle = .short
let dateString = formatter.string(from: Date())
let amRange = dateString.range(of: formatter.amSymbol)
let pmRange = dateString.range(of: formatter.pmSymbol)
return !(pmRange == nil && amRange == nil)
}()
}
// TODO: Use new @ThreadSpecific when it works???
// DateFormatters are notoriously slow to create, so it's best to share them.
// However, they're not thread safe, so this returns one per thread.
extension ISO8601DateFormatter {
static public var shared : ISO8601DateFormatter {
get {
let threadDict = Thread.current.threadDictionary
let key = "com.relium.swift.isoDateFormatter"
if let formatter = threadDict[key] as? ISO8601DateFormatter {
return formatter
}
else {
let newFormatter = ISO8601DateFormatter()
threadDict[key] = newFormatter
return newFormatter
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment