js将日期格式转换为YYYY-MM-DD HH:MM:SS

1、百度不少js将日期格式转换为YYYY-MM-DD HH:MM:SS 。可是都略显复杂,所以这里总结了一下,自己找到的,方便自己学习和使用。

方法一:

项目源码:
$(\"#createTime\").text((new Date(jumpParams.createDate.time).Format(\"yyyy-MM-dd hh:mm:ss\")));
$(\"#updateTime\").text((new Date(jumpParams.updateDate.time).Format(\"yyyy-MM-dd hh:mm:ss\")));
关键点:
xxx.Format(\"yyyy-MM-dd hh:mm:ss\");调用这句话就可以将Sun May 27 2018 11:08:09 GMT+0800 (中国标准时间)格式的时间转换为\"2018-05-27 11:08:09\"格式的时间。

方法二:

项目源码:
$(\"#createTime\").text((ChangeDateFormat(new Date(jumpParams.createDate.time))));
$(\"#updateTime\").text((ChangeDateFormat(new Date(jumpParams.updateDate.time))));
封装方法调用:
function ChangeDateFormat(date) {
 return date.Format(\"yyyy-MM-dd hh:mm:ss\");
}

关键点:
注意括号和自己的时间格式即可。

可以使用浏览器工具,对转换进行查看:

js将日期格式转换为YYYY-MM-DD HH:MM:SS

其他方法

function formatDate(date,cut) {
 var date = new Date(date);
 var YY = date.getFullYear() + cut;
 var MM =
 (date.getMonth() + 1 < 10
  ? \"0\" + (date.getMonth() + 1)
  : date.getMonth() + 1) + cut;
 var DD = date.getDate() < 10 ? \"0\" + date.getDate() : date.getDate();
 var hh =
 (date.getHours() < 10 ? \"0\" + date.getHours() : date.getHours()) + \":\";
 var mm =
 (date.getMinutes() < 10 ? \"0\" + date.getMinutes() : date.getMinutes()) +
 \":\";
 var ss = date.getSeconds() < 10 ? \"0\" + date.getSeconds() : date.getSeconds();
 return YY + MM + DD + \" \" + hh + mm + ss;
}
 

正则方法

function farmatDate(time, fmt) {
 if (/(y+)/.test(fmt) {
  fmt = fmt.replace(RegExp.$1, date.getFullYear() + \'\').substr(4 - RegExp.$1.length);
 }

 let o = {
  \'M+\': getMonth() + 1,
  \'d+\': getDay(),
  \'h+\': getHours(),
  \'m+\': getMinutes(),
  \'s+\': getSeconds()
 };

 for (let key in o) {
  if(RegExp(`(${key})`.test(fmt)) {
   let str = o[key] + \'\';
   fmt = fmt.replace(RegExp.$1, str.length === 2 ? str:padLeftZero(str);
  }
 }
 return fmt;
}

// 函数 padLeftZero 的作用:如果月份为1位(如9),则在其左边补0(变为09)
function padLeftZero(str) {
 return \'00\' + substr(str.length);
}

// 举例
let res = formatDate(\'1469261964000\', \'yyyy-MM-dd hh:mm\');
console.log(res); // 2016-07-06 16:19
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容