So I have a function that converts a specified local time, to UTC (Time starts and ends as a string)
I need to add a duration (lets say 1.5 hours) to this time, which may end up going into the next day so I believe I need to use Calendar, and not timeInterval.
I'm a little clueless on how this is done, the documentation isn't the greatest on this and I'm not good with Swift.
Here is what I have so far.
import Foundation
func localToUTC(date:String, originTimeZone:String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy HH:mm"
dateFormatter.timeZone = TimeZone(identifier: originTimeZone)
let dt = dateFormatter.date(from: date)
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = "MM/dd/yyyy HH:mm"
return dateFormatter.string(from: dt!)
}
print(localToUTC(date: "05/01/2021 15:37", originTimeZone: "America/Boise"))
Just to be clear, I am trying to add another parameter to my function (or make a new function, doesn't matter) to add a duration to the UTC time that my current function outputs.
To put things into context, let's say a flight departs at 15:37 local time (Boise, for example, which is 6 for UTC conversion).
So the flight departs at 21:37 UTC on 5/1/2021. The flight duration is 4 hours.
I would like an output of 5/2/2021 01:37 UTC.
CodePudding user response:
Just add the flight duration to the resulting date object. Note also that you shouldn't force unwrap the result as it might crash your app. Make sure to return nil in case you pass an invalid string. Something like:
func localToUTC(date: String, originTimeZone: String, duration: TimeInterval) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.locale = .init(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "MM/dd/yyyy HH:mm"
guard let timezone = TimeZone(identifier: originTimeZone) else { return nil }
dateFormatter.timeZone = timezone
guard let dt = dateFormatter.date(from: date) else { return nil }
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
return dateFormatter.string(from: dt.addingTimeInterval(duration))
}
print(localToUTC(date: "05/01/2021 15:37", originTimeZone: "America/Boise", duration: 4 * 60 * 60) ?? "nil")
This will print
05/02/2021 01:37