前端将UTC时间格式转化为本地时间格式~~uniapp写法

UTC时间格式是什么

首先我们先简单的了解一下:UTC时间(协调世界时,Coordinated Universal Time)使用24小时制,以小时、分钟、秒和毫秒来表示时间

复制代码
HH:mm:ss.SSS
  • HH 表示小时,取值范围为00到23。
  • mm 表示分钟,取值范围为00到59。
  • ss 表示秒,取值范围为00到59。
  • SSS 表示毫秒,取值范围为000到999。

需要注意的是,UTC时间不考虑夏令时或时区的影响,因此它是一种标准的时间表示方法,不会受到地理位置的变化而改变。

如何转化呢?

我们先随便准备一组数据,能用就行哈

假设下方的数据就是我们冲接口中获取到的

复制代码
				list: [{
						"id": 20,
						"goods_id": 20,
						"task_id": null,
						"deduct_num": 120,
						"integral_num": null,
						"type": 2,
						"created_at": "2023-08-31T02:56:02.000000Z"
					},
					{
						"id": 19,
						"goods_id": 29,
						"task_id": null,
						"deduct_num": 60,
						"integral_num": null,
						"type": 2,
						"created_at": "2023-08-31T02:55:44.000000Z"
					},
					{
						"id": 18,
						"goods_id": 12,
						"task_id": null,
						"deduct_num": 60,
						"integral_num": null,
						"type": 2,
						"created_at": "2023-08-31T02:41:32.000000Z"
					},
					{
						"id": 17,
						"goods_id": 9,
						"task_id": null,
						"deduct_num": 220,
						"integral_num": null,
						"type": 2,
						"created_at": "2023-08-31T02:23:40.000000Z"
					},
					{
						"id": 16,
						"goods_id": 25,
						"task_id": null,
						"deduct_num": 40,
						"integral_num": null,
						"type": 2,
						"created_at": "2023-08-31T02:18:09.000000Z"
					},
					{
						"id": 15,
						"goods_id": 30,
						"task_id": null,
						"deduct_num": 160,
						"integral_num": null,
						"type": 2,
						"created_at": "2023-08-31T01:15:15.000000Z"
					}
				],

使用v-for指令遍历list数组,然后调用convertUTCtoLocal方法将每个对象的created_at字段从UTC时间格式转换为本地时间格式。最终,显示本地时间在界面上。

记得在实际应用中,确保你的时间数据以正确的格式和类型存在,并且适当地处理可能的错误情况

复制代码
  convertUTCtoLocal(utcTime) {
      const utcDate = new Date(utcTime);
      const localDate = new Date(utcDate.getTime() + utcDate.getTimezoneOffset() * 60000);
      return localDate.toLocaleString();
    }

页面渲染部分

复制代码
  <ul>
      <li v-for="(item, index) in list" :key="index">
        <p>ID: {{ item.id }}</p>
        <p>本地时间: {{ convertUTCtoLocal(item.created_at) }}</p>
      </li>
    </ul>

最终效果

相关推荐
QQ1__8115175152 小时前
Spring boot名城小区物业管理系统信息管理系统源码-SpringBoot后端+Vue前端+MySQL【可直接运行】
前端·vue.js·spring boot
钛态2 小时前
前端微前端架构:大项目的救命稻草还是自找麻烦?
前端·vue·react·web
一粒黑子2 小时前
【实战解析】阿里开源 PageAgent:纯前端 GUI Agent,一行JS让网页支持自然语言操控
前端·javascript·开源
独角鲸网络安全实验室2 小时前
2026微信小程序抓包全解析:从实操落地到合规风控,解锁前端调试新范式
前端·微信小程序·小程序·抓包·系统代理绕过·https证书严格校验·进程隔离
紫微AI2 小时前
前端文本测量成了卡死一切创新的最后瓶颈,pretext实现突破了
前端·人工智能·typescript
GISer_Jing2 小时前
AI前端(From豆包)
前端·aigc·ai编程
IT枫斗者2 小时前
前端部署后如何判断“页面是不是最新”?一套可落地的版本检测方案(适配 Vite/Vue/React/任意 SPA)
前端·javascript·vue.js·react.js·架构·bug
测试修炼手册2 小时前
[测试技术] 深入理解 JSON Web Token (JWT)
前端·json
AI老李2 小时前
2026 年 Web 前端开发的 8 个趋势!
前端
里欧跑得慢2 小时前
15. Web可访问性最佳实践:让每个用户都能平等访问
前端·css·flutter·web