Swift:UTC 和本地时间转换

应用场景

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

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...