I receive a date
let slotDateString: String = "2023-12-06T15:45:00+04:00"
I have two formatters:
var iso8601FormatterWithFullTimeZone: DateFormatter {
let formatter = DateFormatter(withFormat: "yyyy-MM-dd'T'HH:mm:ssZZZZZ")
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = .current
return formatter
}
var hoursMinutesFormatter: DateFormatter {
let formatter = DateFormatter(withFormat: "HH:mm")
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = .current
return formatter
}
When I run the following code:
let dateFormatter: DateFormatter = .iso8601FormatterWithFullTimeZone
let hoursMinutesFormatter: DateFormatter = .hoursMinutesFormatter
guard let slotDate: Date = dateFormatter.date(from: slotDateString) else {
return
}
let slotHour: String = hoursMinutesFormatter.string(from: slotDate)
The slotDate
returns me 2023-12-06 12:45:00 +0000
and
the slotHour
returns me "12:45"
I live in timezone +01:00, but I want to get a date and an hour that take into account offset given in the original string.
So slotDate
should have value of something like
2023-12-06 15:45:00 +4000
or 2023-12-06 12:45:00 +0100
and
slotHour
should have exactly "15:45"
You can drop the timezone part and then get the hour:
let slotDateString = String("2023-12-06T15:45:00+01:00".dropLast(6)) // 👈 Drop timezone from the string
var iso8601FormatterWithFullTimeZone: DateFormatter {
let formatter = DateFormatter(withFormat: "yyyy-MM-dd'T'HH:mm:ss") // 👈 No timezone in the formatter
,,,
}
So the slotHour
would be exactly "15:45"