Converting Date object to string to implement function
function formatDate(time, format = "Y-MM-dd HH:mm:ss") {
/**
Format character description
Y Four digit year 2021
The last two examples of Y year number 21
M The number of monthly units does not make up 0 example 1
MM Example 01 of supplement 0 for monthly unit number
d Example 2 of not adding 0 to the number of units per day
dd Example 02 of making up 0 for daily single digit
H 24-hour system, unit number does not make up 0 example 3
HH 24-hour system, unit number complements 0.03
h 12 hour system, unit number does not make up 0 example 3
hh 12 hour system, unit number makes up 0.03
m The unit number of minutes does not make up 0 example 4
mm Example 04 of making up 0 in minutes
s second Unit number does not make up 0 example 5
ss second Unit number complements 0 example 05
*/
let date = new Date(time);
let yearFull = date.getFullYear().toString();
let yearTwoDigits = yearFull.substr(2, 2);
let month = date.getMonth() + 1; // The month starts at 0, so add 1
let day = date.getDate();
let hour = date.getHours(); // 24-hour system
let hourTwelve = hour % 12; // 12 hour system
let min = date.getMinutes();
let sec = date.getSeconds();
let preArr = Array.apply(null, Array(10)).map(function(elem, index) {
return "0" + index;
}); // Create an array with a length of 10, and the format is 00 01 02 03, which is used to fill 0 for month, hour, minute, etc
let newTime = format
.replace(/Y/g, yearFull)
.replace(/y/g, yearTwoDigits)
.replace(/MM/g, preArr[month] || month)
.replace(/M/g, month)
.replace(/dd/g, preArr[day] || day)
.replace(/d/g, day)
.replace(/HH/g, preArr[hour] || hour)
.replace(/H/g, hour)
.replace(/hh/g, preArr[hourTwelve] || hourTwelve)
.replace(/h/g, hourTwelve)
.replace(/mm/g, preArr[min] || min)
.replace(/m/g, min)
.replace(/ss/g, preArr[sec] || sec)
.replace(/s/g, sec);
return newTime;
}
//Run the test
formatDate(new Date().getTime()); // 2021-02-05 10:53:42
Formatdate (New date(). Gettime(), "mm / DD / yyyy")// February 5, 2021
formatDate(new Date().getTime(), "y-MM-dd"); // 21-02-05
let str_datetime = "2021/02/05 09:05:05".replace(/-/g,"/");
formatDate(new Date(str_ Datetime). Gettime (), "today is Y / mm / DD H: M: s")// Today is 2021-02-05 09:05:05
formatDate(new Date(str_ Datetime). Gettime (), "today is Y / mm / DD HH: mm: SS")// Today is 2021-02-05 09:05:05