Skip to content

Instantly share code, notes, and snippets.

@mluton
Last active August 8, 2023 12:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mluton/98ab2b82bd18f7a7f762 to your computer and use it in GitHub Desktop.
Save mluton/98ab2b82bd18f7a7f762 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
}
}
}
@racer1988
Copy link

In my opinion, to have better localized results, you should change line 13 to

      newDateFormatter.dateFormat = NSDateFormatter.dateFormatFromTemplate(format, options: 0, locale: currentLocale)

so format will adapt to country (example is month difference between UK and US)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment