Home > Article > Web Front-end > How to convert timestamp format in js
下面我就为大家分享一篇js实现把时间戳转换为yyyy-MM-dd hh:mm 格式(es6语法),具有很的参考价值,希望对大家有所帮助
如下所示:
function formatDate(date,fmt) { if(/(y+)/.test(fmt)){ fmt = fmt.replace(RegExp.$1,(date.getFullYear()+'').substr(4-RegExp.$1.length)); } let o = { 'M+':date.getMonth() + 1, 'd+':date.getDate(), 'h+':date.getHours(), 'm+':date.getMinutes(), 's+':date.getSeconds() }; // 遍历这个对象 for(let k in o){ if(new RegExp(`(${k})`).test(fmt)){ // console.log(`${k}`) console.log(RegExp.$1) let str = o[k] + ''; fmt = fmt.replace(RegExp.$1,(RegExp.$1.length===1)?str:padLeftZero(str)); } } return fmt; }; function padLeftZero(str) { return ('00'+str).substr(str.length); }
let TimeNow = 1514374627*1000
let newTime = new Date(TimeNow)
formatDate(newTime,'yyyy-MM-dd hh:mm') //2017-12-27 19:37
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
The above is the detailed content of How to convert timestamp format in js. For more information, please follow other related articles on the PHP Chinese website!