关于Json格式中时间格式转化问题
2017-10-07 10:41
573 查看
如果不经转化修改,一般情况下json时间格式一般是如下格式:
Date(1436595149269)
通常我们用ajax获取下来的json数据,如果有时间,都是这种格式.其中的数字表示的是1970年1月1日至今的毫秒数.
针对如上有以下两种方式来解决:
示例:
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格式对象返回页面时间字段显示NANA的问题
- 关于JSON数据格式返回时间数据格式化问题
- 关于js中日期时间格式的各种转化问题
- 关于Web项目里的给表单验证控件添加结束时间不得小于开始时间的验证方法,日期转换和前台显示格式之间,还有JSON取日期数据格式转换成标准日期格式的问题
- 遇到的问题------------时间格式转化时java.text.ParseException: Unparseable date: ""异常
- 关于json转换bean,Date为当前系统时间的问题
- 关于 jsonp 跨域后返回 json 数据格式的问题
- 关于Gson转换Json格式导致“=”乱码的问题!
- 关于jsp页面显示的时间格式和Oracle数据库中的格式不一样的问题
- 关于datatables 接受json数据格式的问题
- 关于http接口开发中json格式数据编码问题处理
- 遇到的问题------------时间格式转化时java.text.ParseException: Unparseable date: ""异常
- 关于系统时间格式的问题
- C#关于DateTime得到的当前时间的格式问题(转 自己用)
- json时间的格式转化为正常时间格式
- 关于Gson无法将匿名类转化为json字符串的问题
- 关于oracle时间转换格式问题
- 关于Android ArrayList与json数据格式的转化
- 【Json】JSONObejct格式转化问题
- 关于MVC中返回JSON格式数据提示下载的问题