What is UTC time format
First, let’s take a brief look at it: UTC time (Coordinated Universal Time) uses a 24-hour clock and represents time in hours, minutes, seconds and milliseconds.
HH:mm:ss.SSS
HH
Indicates the hour, the value range is 00 to 23.mm
Indicates the minute, the value range is 00 to 59.ss
Represents seconds, the value range is 00 to 59.SSS
Represents milliseconds, the value range is 000 to 999.
It should be noted that UTC time does not take into account the effects of daylight saving time or time zones, so it is a standard time representation method that will not be changed by changes in geographical location.
How to convert it?
Let's prepare a random set of data first, as long as it can be used.
Assume that the data below is what we obtained from the interface
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"
}
],
Use v-for
the directive to iterate through list
the array and call convertUTCtoLocal
methods to convert each object's created_at
fields from UTC time format to local time format. Finally, the local time is displayed on the interface.
Remember to ensure that your time data exists in the correct format and type, and that possible error conditions are handled appropriately
convertUTCtoLocal(utcTime) {
const utcDate = new Date(utcTime);
const localDate = new Date(utcDate.getTime() + utcDate.getTimezoneOffset() * 60000);
return localDate.toLocaleString();
}
Page rendering part
<ul>
<li v-for="(item, index) in list" :key="index">
<p>ID: {
{ item.id }}</p>
<p>本地时间: {
{ convertUTCtoLocal(item.created_at) }}</p>
</li>
</ul>
final effect