如何使用格式将JSON日期格式化为Javascript日期 [英] How to format JSON Date as Javascript date with format

查看:122
本文介绍了如何使用格式将JSON日期格式化为Javascript日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的日期为

Quote:

/ Date(1352656800000)/

/Date(1352656800000)/





如何使它成为2012年1月11日。



How to make it as Jan 11,2012.

推荐答案


Yaseer -



您可以使用:

Yaseer -

You can use:

var completedDateText = "/Date(1352656800000)/";
var completedDate = new Date(parseInt(completedDateText.replace("/Date(", "").replace(")/")));
alert(completedDate.toDateString());



或者,如果你想格式化你的日期


Or, if you want to format your date

var completedDateText = "/Date(1352656800000)/";
    var completedDate = new Date(parseInt(completedDateText.replace("/Date(", "").replace(")/")));
    // from http://www.webdeveloper.com/forum/showthread.php?67608-Date()-format-as-mm-dd-yyyy
    var dd = completedDate.getDate();
    var mm = completedDate.getMonth() + 1; //January is 0! 
    var yyyy = completedDate.getFullYear(); 
    if(dd<10){dd='0'+dd} 
    if(mm<10){mm='0'+mm}
    alert('Completed date is ' + mm + '/' + dd + '/' + yyyy);


正如我所见,这是一个JavaScript时间戳。

好​​的: 1352656800000 表示 Sun,2012年11月11日18:00 :00 GMT

因此,首先将JSON字符串解码为对象。比解析它和每个匹配的字段(因为你没有给出整个结构,你必须找到它们),使用以下函数(假设,字段值格式为 / Date(1352656800000)/ ):



As I see, it is a JavaScript timestamp.
Ok: 1352656800000 means Sun, 11 Nov 2012 18:00:00 GMT
So, first of all decode the JSON string to an object. Than parse it and for every matching field (since you have not given the whole structure, you have to find them), use the following function (supposing, that the field value format is /Date(1352656800000)/):

<script>
function ParseDate(input){ 
	theDate = new Date(parseInt(input.substring(6,19)));
	return theDate.toGMTString();
}

alert(ParseDate("/Date(1352656800000)/"));
</script>





如果您需要格式化,或者您必须使用时间戳作为javascript日期对象,只需更改返回的表达式。



If you need formatting, or you have to use the timestamp as javascript date object, just change the returned expression.


function parseJsonDate(jsonDate) {
               var offset = new Date().getTimezoneOffset() * 60000;
               var parts = /\/Date\((-?\d+)([+-]\d{2})?(\d{2})?.*/.exec(jsonDate);

               if (parts[2] == undefined)
                   parts[2] = 0;

               if (parts[3] == undefined)
                   parts[3] = 0;
               return new Date(+(parts[1]) + (parts[2]) * 3600000 + (parts[3]) * 60000);
           }


这篇关于如何使用格式将JSON日期格式化为Javascript日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆