Last active
August 8, 2023 12:04
-
-
Save mluton/98ab2b82bd18f7a7f762 to your computer and use it in GitHub Desktop.
Swift class that instantiates and caches NSDateFormatter objects
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 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
In my opinion, to have better localized results, you should change line 13 to
so format will adapt to country (example is month difference between UK and US)