网站首页 > 技术文章 正文
应用场景
一般服务器存储时间为 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
}
猜你喜欢
- 2025-07-06 为什么前端大佬都推荐用 performance.now() 而非 Date.now()?
- 2025-07-06 实战分享:邀请有礼产品怎么做?(邀请有礼活动)
- 2025-07-06 揭秘:视频播放网站如何精准记录用户观看进度
- 2025-07-06 第七篇 前端基础十问,看看你是否真的掌握扎实?
- 2025-07-06 下单预约送货时间功能设计及思路(预约送货怎么说)
- 2025-07-06 每天一个 Python 库:datetime 模块全攻略,时间操作太丝滑!
- 2025-07-06 前端代码更新,如何优雅地通知用户刷新页面?
- 2024-10-09 JS Date对象的妙用:如何更优雅的计算时间差?
- 2024-10-09 从零开始的前端请求之旅 从零开始学前端开发
- 2024-10-09 如何在上班时间利用终端控制台摸鱼??????
你 发表评论:
欢迎- 593℃几个Oracle空值处理函数 oracle处理null值的函数
- 586℃Oracle分析函数之Lag和Lead()使用
- 574℃0497-如何将Kerberos的CDH6.1从Oracle JDK 1.8迁移至OpenJDK 1.8
- 571℃Oracle数据库的单、多行函数 oracle执行多个sql语句
- 567℃Oracle 12c PDB迁移(一) oracle迁移到oceanbase
- 559℃【数据统计分析】详解Oracle分组函数之CUBE
- 546℃最佳实践 | 提效 47 倍,制造业生产 Oracle 迁移替换
- 540℃Oracle有哪些常见的函数? oracle中常用的函数
- 最近发表
- 标签列表
-
- 前端设计模式 (75)
- 前端性能优化 (51)
- 前端模板 (66)
- 前端跨域 (52)
- 前端缓存 (63)
- 前端react (48)
- 前端aes加密 (58)
- 前端脚手架 (56)
- 前端md5加密 (54)
- 前端路由 (61)
- 前端数组 (73)
- 前端js面试题 (50)
- 前端定时器 (59)
- 前端懒加载 (49)
- 前端获取当前时间 (50)
- Oracle RAC (73)
- oracle恢复 (76)
- oracle 删除表 (48)
- oracle 用户名 (74)
- oracle 工具 (55)
- oracle 内存 (50)
- oracle 导出表 (57)
- oracle 中文 (51)
- oracle的函数 (57)
- 前端调试 (52)
本文暂时没有评论,来添加一个吧(●'◡'●)