如何将"Hours:Minutes:Seconds AM/PM"(UTC时区)转换为Swift中"Hours:Minutes AM/PM"格式的用户时区?

How to convert "Hours:Minutes:Seconds AM/PM"(UTC timezone) to the user's time zone in the format of "Hours:Minutes AM/PM" in Swift?

输入的字符串永远是Hours:Minutes:Seconds AM/PM格式,永远是UTC时区(字符串表示用户所在的日出时间,但只能是UTC ).几个例子是: 10:3:30上午, 2:40:01下午, 12:0:04上午

我想将时间转换为用户的时区,然后去掉秒部分,这样它就只是“小时:分钟 AM/PM”

到目前为止,我认为我可以使用 var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "" } 获取用户的当前时区,但我仍然不知道如何将字符串转换为该时区。有什么建议吗?

使用DateFormatter。一个实例将您的 UTC 时间转换为 Date,另一个实例将 Date 转换为本地化的 String.

let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX") // set locale before format; good to use this locale for fixed date formats
formatter.dateFormat = "h:m:ss a"
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)

请注意 day/month/year 将隐式默认为系统默认值(我看到的是 2000 年 1 月 1 日),但您可以忽略它。