@DTS Engineer Thanks for your quick response. We have one of our users from Dublin who is facing this type of issue. let me try to implement this and I will ask for more help if needed.
Post
Replies
Boosts
Views
Activity
@DTS Engineer Please check above code
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)