JS日期格式的转换

JavaScript018

JS日期格式的转换,第1张

1. 将日期转换为指定的格式:比如转换成 年月日时分秒 这种格式:yyyy-MM-dd hh:mm:ss 或者 yyyy-MM-dd。当然是网上的方法,只是总结下。

可以为Date原型添加如下的方法:

Date.prototype.format = function(fmt) {

var o = {

"M+" : this.getMonth()+1, //月份

"d+" : this.getDate(),//日

"h+" : this.getHours(), //小时

"m+" : this.getMinutes(), //分

"s+" : this.getSeconds(), //秒

"q+" : Math.floor((this.getMonth()+3)/3), //季度

"S" : this.getMilliseconds() //毫秒

}

if(/(y+)/.test(fmt)) {

fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length))

}

for(var k in o) {

if(new RegExp("("+ k +")").test(fmt)){

fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)))

}

}

return fmt

}

比如我们可以这样调用下:

var time1 = new Date().format("yyyy-MM-dd hh:mm:ss")

console.log(time1)

需要准备的材料分别有:电脑、html编辑器、浏览器。

1、首先,打开html编辑器,新建html文件,例如:index.html。

2、在index.html中的<script>标签,输入js代码:var a = 1562060142000document.body.innerText = new Date(a)。

3、浏览器运行index.html页面,此时时间被转化为年月日时分秒打印出来了。

js时间戳转日期格式 formatDate

javascript 时间戳自定义格式转换,支持年月日时分秒等多种形式组合的日期和时间。

使用示例

年、月、日、时、分、秒

var date = jutils.formatDate(new Date(1533686888*1000),"YYYY-MM-DD HH:ii:ss")

console.log(date)

// 2019-07-09 19:44:01

年、月、日、周

var date = jutils.formatDate(new Date(1562672641*1000),"YYYY-MM-DD 周W")

console.log(date)

//2019-07-09 周二

月、日、周 

var date = jutils.formatDate(new Date(1562672641*1000),"MM-DD 周W")

console.log(date)

//07-09 周二

时、分、秒

var date = jutils.formatDate(new Date(1562672641*1000),"HH:ii:ss")

console.log(date)

//19:44:01

源码:

jutils formatDate

参考:

js时间戳转日期格式 formatDate