一種是使用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/