首页 技术 正文
技术 2022年11月12日
0 收藏 398 点赞 4,706 浏览 1868 个字

通常JSON时间一般是这样的格式。

1 /Date(1436595149269)/

通常我们用AJAX获取下来的JSON数据,如果有时间,都是这种格式的。其中,中间的一段数字”1436595149269″表示的是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);
})

另外一个实现


另外,还有一个方式,这个就不需要改原来Date原型了。

<!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>
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,909
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,434
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,249
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,060
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,692
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,730