应用场景
一般服务器存储时间为 UTC 时间(UTC 为世界时间),保证时间的一致性。但是对于前端显示时间的时候,就非常不友好。需要前端将 UTC 时间转换为本地时间显示。
API 以及语言
DateFormatter
Swift
核心逻辑/代码
时间转换的时候,需要先确定转换完成的时间的时区,比如 dateFormatter.timeZone = TimeZone.current
就是确定时区为本地时区。TimeZone
类应用于设置时区,可以使用TimeZone(abbreviation:"时区缩写")
来自定义要转换的时区时间。
示例代码
获取 UTC 上的时间,转换为本地时间
func getLocalDate(from UTCDate: String) -> String {
let dateFormatter = DateFormatter.init()
// UTC 时间格式
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let utcTimeZone = TimeZone(abbreviation: "UTC")
dateFormatter.timeZone = utcTimeZone
guard let dateFormatted = dateFormatter.date(from: UTCDate) else {
return ""
}
// 输出格式
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "yyyy:MM:dd HH:mm:ss"
let dateString = dateFormatter.string(from: dateFormatted)
return dateString
}
原文地址:https://www.cnblogs.com/shsuper
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。