美文网首页iOS OC 学习手册
Swift:UTC 和本地时间转换

Swift:UTC 和本地时间转换

作者: 我为双鱼狂 | 来源:发表于2021-06-23 21:27 被阅读0次

应用场景

一般服务器存储时间为 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
}

相关文章

网友评论

    本文标题:Swift:UTC 和本地时间转换

    本文链接:https://www.haomeiwen.com/subject/ueliyltx.html