This is the 8th day of my participation in Gwen Challenge

1. Introduction

I received a message from my friend asking me: How do I convert the UTC time to YYYY-MM-DD HH:MM:SS?

When I first saw it, what was it, never seen this format? Hence the output of this article, which shows how to format UTC time.

2. Implementation scheme

‘2021-06-23T07:00:00.5872’ is in UTC time format. New Date() creates a Date object that can be used to get a timestamp, format a time, and so on.

Function formatDate (v){if(v){const year = v.gefullYear () const month = v.getMonth() + 1 < 10 ? `0${v.getMonth() + 1 }`: v.getMonth() const day = v.getDate() + 1 < 10 ? `0${v.getDate() + 1 }`: v.getDate() const hour = v.getHours() < 10 ? `0${v.getHours()}`: v.getHours() const minute = v.getMinutes() < 10 ? `0${v.getMinutes()}`: v.getMinutes() const second = v.getSeconds() < 10 ? `0${v.getSeconds()}`: v.getSeconds() return `${year}-${month}-${day} ${hour}:${minute}:${second}` } return '' } const createTime = '2021-06-23T07:00:00.5872' // Here is the key, convert UTC format to Date object!!!!!! -> specify Date const TMP = new Date(createTime) // Different from new Date() -> Return a Date object: current time console.log(formatDate(TMP))Copy the code

So far you have solved your problem, the latter can not see. But suggestions have come, learning under better yo ~

3. New Date() compatible with IOS

We often use the format YYYY-MM-DD HH:MM:SS to represent dates. We also convert strings in this format to Date objects as follows

const Time = '2021-06-28 15:26:45'
Copy the code

The code is normal on Chrome, 360 and other Web browsers and Android devices; Error: Invalid Date: Invalid Date. Solution:

// Replace (/-/g, "/")) const Time = '2021-06-28 15:26:45' Time = new Date(time.replace (/-/g, "/"));Copy the code

4. Write at the end

If there is a mistake, please leave a message, will be corrected in time! If feel helpful to you, please click a like or collect it!