您的位置:首页 > Web前端 > JavaScript

关于Json格式中时间格式转化问题

2017-10-07 10:41 573 查看
如果不经转化修改,一般情况下json时间格式一般是如下格式:

Date(1436595149269)

通常我们用ajax获取下来的json数据,如果有时间,都是这种格式.其中的数字表示的是1970年1月1日至今的毫秒数.

针对如上有以下两种方式来解决:

实现一:

第一步:替换掉Date()

对外暴露的函数,替换掉/Date( )

function convertTime(jsonTime, format) {
var date = new Date(parseInt(jsonTime.replace("/Date(", "").replace(")/", ""), 10));
var formatDate = date.format(format);
return formatDate;
}


第二步:将数字时间转换为可视化的yyyy-MM-dd HH:mm:ss的格式

先扩展一下javascript的Date类型,增加一个函数,用于返回我们想要的 yyyy-MM-dd HH:mm:ss 这种时间格式

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;
}


示例:

$(function () {
var dt = '/Date(1436595149269)/';
var formatTime1 = convertTime(dt, "yyyy-MM-dd hh:mm:ss");//2015-07-11 14:12:29
$("#div1").text(formatTime1);
var formatTime2 = convertTime(dt, "yyyy年MM月dd日 hh时mm分ss秒");//2015年07月11日 14时12分29秒
$("#div2").text(formatTime2);
})


另一种方式:

<!doctype html>
<html>
<head>
<title>JSON时间格式化(/Date()转换为yyyy-MM-dd HH:mm:ss)</title>
</head>
<body>
<script>
//yyyy-MM-dd HH:mm:SS
function getDateTime(date) {
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hh = date.getHours();
var mm = date.getMinutes();
var ss = date.getSeconds();
return year + "-" + month + "-" + day + " " + hh + ":" + mm + ":" + ss;
}
//调用的是这个方法
function ConvertJSONDateToJSDate(jsondate) {
var date = new Date(parseInt(jsondate.replace("/Date(", "").replace(")/", ""), 10));
return date;
}
var date = "/Date(1379944571737)/";
alert(getDateTime(ConvertJSONDateToJSDate(date)));
</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  json 数据 ajax