Reputation: 326
I am aware about similar questions, however, I couldn't find this exact one:
In an iOS application, I am receiving a date in the format dd-MM-yyyy HH:mm:ss
(i.e. 30-07-2019 12:05:00) in GMT +2h, and I like to convert it to yyyy-MM-dd HH:mm:ss +0000
in GMT ±0h (i.e. 2019-07-30 10:05:00 +0000).
How can I do this?
Upvotes: 1
Views: 226
Reputation: 239
Firstly create 2 DateFormatter. First dateFormat for create date from dateString. Second dateFormat for create string from created date.
Code:
let dateString = "30-07-2019 12:05:00"
let dateFormatForDate = DateFormatter()
dateFormatForDate.timeZone = TimeZone(abbreviation: "GMT+2")
dateFormatForDate.dateFormat = "dd-MM-yyyy HH:mm:ss"
//date
let date = dateFormatForDate.date(from: dateString)
let dateFormatForString = DateFormatter()
dateFormatForString.timeZone = TimeZone(abbreviation: "GMT")
dateFormatForString.dateFormat = "yyyy-MM-dd HH:mm:ss +0000"
//string
let formattedDateString = dateFormatForString.string(from: date!)
Result:
dateString: 30-07-2019 12:05:00
formattedDateString: 2019-07-30 09:05:00 +0000
Upvotes: 3
Reputation: 6213
extension Date {
func convert(_ from: TimeZone, toTimeZone: TimeZone) -> Date {
let delta = TimeInterval(toTimeZone.secondsFromGMT() - from.secondsFromGMT())
return addingTimeInterval(delta)
}
}
let dateFmt = DateFormatter()
dateFmt.timeZone = TimeZone(abbreviation: "GMT+2")
dateFmt.dateFormat = "dd-MM-yyyy HH:mm:ss"
if let date = dateFmt.date(from: "30-07-2019 12:05:00") {
let localDate = date.convert(TimeZone(abbreviation: "GMT+02")!, toTimeZone: TimeZone(abbreviation: "GMT+00")!)
}
Upvotes: 0