【js】js中将时间戳转化成 YYYY-MM-DD HH:mm:ss的3种办法

avatar
作者
猴君
阅读量:0

方法一:dayjs(最推荐)

npm install dayjs # 或者 yarn add dayjs 
const dayjs = require('dayjs');   // 假设你有一个时间戳 const timestamp = 1650000000000; // 示例时间戳   // 使用dayjs转换时间戳 const formattedDate = dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss');   console.log(formattedDate); // 输出转换后的日期和时间 

方法二:moment.js

npm install moment 
// 引入Moment.js库 const moment = require('moment');   // 假设你有一个时间戳 const timestamp = 1609459200000; // 例如:2021年1月1日 00:00:00的时间戳   // 使用Moment.js转换时间戳为YYYYMMDD HH:mm:ss格式 const formattedDate = moment(timestamp).format('YYYYMMDD HH:mm:ss');   console.log(formattedDate); // 输出:20210101 00:00:00 

方法三:原生js(不推荐)

function timestampToYMDHMS(timestamp) {   const date = new Date(timestamp);   const year = date.getUTCFullYear();   const month = ('0' + (date.getUTCMonth() + 1)).slice(-2); // 月份是从0开始的   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); // 输出格式如:20230310 12:34:56 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!