方法一: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
附:判断日期是否已过
代码如下(示例):
var timestampnow = date.parse(new date());//获取当前时间戳 if(timestamp-timestampnow<0){//根据时间戳的差判断 this.setdata({ ispast:true }) }else{ this.setdata({ ispast:false }) }
总结
到此这篇关于js中将时间戳转化成yyyy-mm-dd hh:mm:ss的3种实现办法的文章就介绍到这了,更多相关js时间戳转化yyyy-mm-dd hh:mm:ss内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论