js中的日期

在前端获取到文本类型的日期格式Wie“yyyy-mm-dd”后,若要在前端进行日期比较,需要先将文本转为日期格式Date

var startDate = new Date(startMonth.replace(/-/g,'/'));将日期格式中的-替换为/
就可以进行大小比较了。
 
同时

   js中接收到后台返回的json字符串中的日期类型的字段都变成了一串数字,形如:1500341149000。所以我们需要将这个串格式化形如:2017-07-18 09:25:49.

   直接上代码:

    1、先把字符串进行日期的封装 var date = new Date(1500341149000);

    2、封装转换函数

Date.prototype.format = function(format){
var date = {
"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+)/i.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
}
for (var k in date) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length == 1
? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
}
}
return format;
}
3、调用函数格式化:date.Format("yyyy-MM-dd hh:mm:ss");

 

  这样就可以完成转换了

posted @ 2018-08-11 17:20  jamesinsun  阅读(218)  评论(0)    收藏  举报