-
-
Save alemar11/f7025f48c5508c191432 to your computer and use it in GitHub Desktop.
Swift class that instantiates and caches NSDateFormatter objects
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 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