The input string will always be in the Hours:Minutes:Seconds AM/PM format, and it will always be in the UTC Timezone (The string represents the sunrise time where the user is, but only in UTC). A few examples are: 10:3:30 AM, 2:40:01 PM, 12:0:04 AM
I want to convert the time to the user's timezone and then get rid of the seconds component, so that it is just "Hours:Minutes AM/PM"
So far, I think I can use
var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "" }
to get the user's current timezone, but I still don't know how to convert the string to that timezone. Any suggestions?
CodePudding user response:
Use DateFormatter
. One instance to convert from your UTC time to a Date
and another to convert from that Date
to a localized String
.
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "h:m:ss a" // examples are somewhat inconsistent
formatter.timeZone = TimeZone(abbreviation: "UTC")
let date = formatter.date(from: "10:3:30 AM")! // whichever input string you have
let localFormatter = DateFormatter() // time zone and locale default to system's
localFormatter.dateFormat = "hh:mm a" // if you don't want a zero padding single digits then use "h:m a"
let string = localFormatter.string(from: date)
Note the day/month/year will implicitly default to the default for the system, (I'm seeing January 1 2000) but you can presumably ignore that.