欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

js实现把时间戳转换为yyyy-MM-dd hh:mm 格式(es6语法)

程序员文章站 2022-08-13 11:17:53
如下所示: function formatdate(date,fmt) { if(/(y+)/.test(fmt)){ fmt = fmt.replace...

如下所示:

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

以上这篇js实现把时间戳转换为yyyy-mm-dd hh:mm 格式(es6语法)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。