方法一:dayjs(最推荐)
npm install dayjs
# 或者
yarn add dayjs
const dayjs = require('dayjs');
const timestamp = 1650000000000;
const formattedDate = dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss');
console.log(formattedDate);
方法二:moment.js
npm install moment
const moment = require('moment');
const timestamp = 1609459200000;
const formattedDate = moment(timestamp).format('YYYYMMDD HH:mm:ss');
console.log(formattedDate);
方法三:原生js(不推荐)
function timestampToYMDHMS(timestamp) {
const date = new Date(timestamp);
const year = date.getUTCFullYear();
const month = ('0' + (date.getUTCMonth() + 1)).slice(-2);
const day = ('0' + date.getUTCDate()).slice(-2);
const hours = ('0' + date.getUTCHours()).slice(-2);
const minutes = ('0' + date.getUTCMinutes()).slice(-2);
const seconds = ('0' + date.getUTCSeconds()).slice(-2);
return `${year}${month}${day} ${hours}:${minutes}:${seconds}`;
}
const timestamp = Date.now();
const formattedDate = timestampToYMDHMS(timestamp);
console.log(formattedDate);