素材巴巴 > 程序开发 >

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

程序开发 2023-09-03 17:07:45

UTC时间格式是什么

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

HH:mm:ss.SSS
 

需要注意的是,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();}

页面渲染部分

  
  • ID: {{ item.id }}

    本地时间: {{ convertUTCtoLocal(item.created_at) }}

最终效果

5741beb57d254a16b94618550e895c2f.png

 

 

 

 


标签:

上一篇: 查询图片 下一篇:
素材巴巴 Copyright © 2013-2021 http://www.sucaibaba.com/. Some Rights Reserved. 备案号:备案中。