轻松搞定javascript日期格式化问题

Date.prototype.format = function(f){
var d = this
f = f || "yyyy-MM-dd hh:mm:ss"
return f.replace(/[yMdhms]+/g, function(item){
switch (item) {
case "yyyy":
return d.getFullYear()
break
case "MM":
return +d.getMonth() + 1 < 10 ? "0" + (+d.getMonth() + 1) : +d.getMonth() + 1
break
case "dd":
return +d.getDate() < 10 ? "0" + d.getDate() : d.getDate()
break
case "hh":
return +d.getHours() < 10 ? "0" + d.getHours() : d.getHours()
break
case "mm":
return +d.getMinutes() < 10 ? "0" + d.getMinutes() : d.getMinutes()
break
case "ss":
return +d.getSeconds() < 10 ? "0" + d.getSeconds() : d.getSeconds()
break
}
})
}

var d = new Date()
console.log(d.format())
console.log(d.format("yyyy/MM/dd"))

posted @ 2017-01-14 16:45  Fetion  阅读(141)  评论(0编辑  收藏  举报