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

时间类型转json后格式化显示方法

2015-09-28 11:59 597 查看
当数据库的关于时间的字段类型为data的时候,在查询取到值转为json数据格式以后就会变成一串数字,如果我们直接显示在页面上是看不出时间的,所以需要格式化时间,这里仅记录js的格式化方法。

在获取到数据后我们用以下方式格式化时间://格式化JSON时间格式
function jsonDateFormat(jsonDate) {

//json日期格式转换为正常格式

var jsonDateStr = jsonDate.toString();//此处用到toString()是为了让传入的值为字符串类型,目的是为了避免传入的数据类型不支持.replace()方法
try {
var date = new Date(parseInt(jsonDateStr.replace("/Date(", "").replace(")/", ""), 10));
var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
var milliseconds = date.getMilliseconds();
return date.getFullYear() + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds + "." + milliseconds;
} catch (ex) {
return "时间格式转换错误";
}
}

使用该方法转换后,输出的时间格式就是自己自定义的了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息