Post

Replies

Boosts

Views

Activity

Reply to The DateFormatter is returning wrong date format 2024-04-23T7:52:49.352 AMZ, 2024-05-23T11:16:24.706 a.m.Z
This is our actual code. enum DateTimeZoneMode { case utc case gmt case local func timeZone() -> TimeZone? { switch self { case .local: return TimeZone.current case .utc: return TimeZone(abbreviation: "UTC") case .gmt: return TimeZone(abbreviation: "GMT") } } } private final class FormatterCache { /// Either the string format or style of the date enum FormatOrStyle: Hashable { case format(String) case style(DateFormatter.Style) } /// The key to use to cache the formatters (combo of tz and format) private struct Key: Hashable { let mode: DateTimeZoneMode let formatOrStyle: FormatOrStyle } private var lock = os_unfair_lock() private var formatters = [Key: DateFormatter]() init() {} func formatter( forMode mode: DateTimeZoneMode, formatOrStyle: FormatOrStyle, shouldDisplayInLocalFormat: Bool = true ) -> DateFormatter { let key = Key(mode: mode, formatOrStyle: formatOrStyle) os_unfair_lock_lock(&lock) defer { os_unfair_lock_unlock(&lock) } let displayLocalFormat = true // or false if let formatter = formatters[key] { formatter.locale = displayLocalFormat ? Locale.current : Locale(identifier: "en_US_POSIX") if mode == .local { // always reset the timezone to keep .local up-to-date formatter.setLocalTimeZone() } return formatter } else { let formatter = DateFormatter() formatter.locale = displayLocalFormat ? Locale.current : Locale(identifier: "en_US_POSIX") switch formatOrStyle { case let .style(style): formatter.dateStyle = style case let .format(format): formatter.dateFormat = format } if mode == .local { formatter.setLocalTimeZone() } else { formatter.timeZone = mode.timeZone() } formatters[key] = formatter return formatter } } } private extension DateFormatter { func setLocalTimeZone() { self.timeZone = DateTimeZoneMode.local.timeZone() } } extension DateFormatter { convenience init (from format: String) { self.init() dateFormat = format } } this is how we call function. and this function gives the wrong date formatterCache.formatter(forMode: timeZone, formatOrStyle: .format(format)).string(from: date)
Jun ’24