我需要为用户将一个TimeZone
转换为另一个TimeZone
,并且正在使用以下代码:
let myTime = "2019-11-02 02:00:00"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = dateFormatter.date(from: myTime)
let source_timezone = NSTimeZone(abbreviation: TimeZone.current.abbreviation()!)
let local_timezone = NSTimeZone.system
let source_EDT_offset = source_timezone?.secondsFromGMT(for: date!)
let destination_EDT_offset = local_timezone.secondsFromGMT(for: date!)
let time_interval : TimeInterval = Double(destination_EDT_offset - source_EDT_offset!)
let final_date = NSDate(timeInterval: time_interval, since: date!)
print(final_date)
但是请在crash nil
这里(source_EDT_offset)
给我。
答案 0 :(得分:1)
这里有一个代码运行方式的清理版本,请注意,在此示例中,我选择了myTime
的“起始”时区
func changeToSystemTimeZone(_ date: Date, from: TimeZone, to: TimeZone = TimeZone.current) -> Date {
let sourceOffset = from.secondsFromGMT(for: date)
let destinationOffset = to.secondsFromGMT(for: date)
let timeInterval = TimeInterval(destinationOffset - sourceOffset)
return Date(timeInterval: timeInterval, since: date)
}
例如,请注意,您需要设置与输入日期(myTime
的时区相匹配的语言环境
let myTime = "2019-11-02 02:00:00"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
if let date = dateFormatter.date(from: myTime), let timeZone = TimeZone(abbreviation: "UTC") {
let offsetedDate = changeToSystemTimeZone(date, from: timeZone)
print(date, Calendar.current.timeZone)
print(offsetedDate, timeZone)
}
2019-11-02 01:00:00 +0000欧洲/斯德哥尔摩(当前)
2019-11-02 02:00:00 +0000 GMT(固定)
更新:添加了用于时区的参数以转换为