Skip to content

Instantly share code, notes, and snippets.

@alemar11
Forked from mluton/CachedDateFormatter.swift
Created November 20, 2015 22:08
Show Gist options
  • Save alemar11/f7025f48c5508c191432 to your computer and use it in GitHub Desktop.
Save alemar11/f7025f48c5508c191432 to your computer and use it in GitHub Desktop.
Swift class that instantiates and caches NSDateFormatter objects
class CachedDateFormatter {
static let sharedInstance = CachedDateFormatter()
var cachedDateFormatters = [String: NSDateFormatter]()
func formatterWith(#format: String, timeZone: NSTimeZone = NSTimeZone.localTimeZone(), locale: NSLocale = NSLocale(localeIdentifier: "en_US")) -> NSDateFormatter {
let key = "\(format.hashValue)\(timeZone.hashValue)\(locale.hashValue)"
if let cachedDateFormatter = cachedDateFormatters[key] {
return cachedDateFormatter
}
else {
let newDateFormatter = NSDateFormatter()
newDateFormatter.dateFormat = format
newDateFormatter.timeZone = timeZone
newDateFormatter.locale = locale
cachedDateFormatters[key] = newDateFormatter
return newDateFormatter
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment