前端时间格式转换:
一行代码搞定的: 时间格式为 2019-07-01 12:00:00
function time(time = +new Date()) {
console.log(time)
var date = new Date(time + 8 * 3600 * 1000); // 增加8小时
return date.toJSON().substr(0, 19).replace('T', ' ');
}
console.log(time(+new Date("2014-10-01 12:00:00")))//里面穿的格式只要符合要求就行例如: 2014/02/12 2014-12-21 时间不传默认00:00:00
日期格式转换 转换成2019-12-12
function date (date) {
var nowdate = new Date(date).toLocaleDateString().replace(///g, '-')
return nowdate
}
日期格式转换 转换成2019/12/12
function date (date) {
var nowdate = new Date(date).toLocaleDateString()
return nowdate
}
日期格式转换成 2019年12月12日
function getdate() {
var now = new Date(),
y = now.getFullYear(),
m = ("0" + (now.getMonth() + 1)).slice(-2),
d = ("0" + now.getDate()).slice(-2);
return y + "-" + m + "-" + d + " " + now.toTimeString().substr(0, 8);
}
正则时间格式化
var date = "2018-10-08 15:22:45"; //格式化掉 时分秒 var newDate=/d{4}-d{1,2}-d{1,2}/g.exec(date) //格式化掉秒 var newDate=/d{4}-d{1,2}-d{1,2} d{1,2}:d{1,2}/g.exec(date)
但是需要注意的是:不过这样转换在某些浏览器上会出现不理想的效果,因为toLocaleDateString()方法是因浏览器而异的,比如 IE为2016年8月24日 22:26:19 格式
搜狗为Wednesday, August 24, 2016 22:39:42
所以最终选用哪一种,看个人以及需求.