一种是使用date提供的方法,另一种是使用第三方库moment.js
方法一:
let val = 1591941383199
dateformat(val)
function dateformat(val) {
let date = new Date(Number(val))
//这里是当时间为个位数时,给它加上引导0,不需要加0的格式的话可以直接获取,最后拼接起来就可以了
//月份得到的是0-11所以需要加1
let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
let hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours()
let muinte = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()
let second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds()
console.log(date.getFullYear() + "年" + month + "月" + day + '日 ' + hour + ":" + muinte + ":" + second)
}
方法二:
引入 moment.js ,然后直接调用方法
<script src="http://cdn.staticfile.org/moment.js/2.24.0/moment.js" ></script>
<script type="text/javascript">
let time = moment(1591941383199).format('YYYY-MM-DD HH:mm:ss')
console.log(time)
</script>
这里使用的是 moment(Number) ,Number即为需要传入的时间戳,format()用来定义转换后的格式
具体可在 moment.js 官方文档中查看 http://momentjs.cn/docs/