問題描述
如何從 JSON.Net 轉換日期時間格式,例如:
How can I convert a date time format from JSON.Net such as:
/日期(1154970000000+0700)/
/Date(1154970000000+0700)/
到 ISO-??格式2011-12-18T23:34:59Z
To ISO-?? format 2011-12-18T23:34:59Z
最好使用 Python 或 Javascript.
Preferably in either Python or Javascript.
我決定選擇后者,因為它在 JS 世界中似乎是使用最廣泛、可讀性最強且自然可排序的.我將按用戶存儲偏移量.
Ive decided on the latter as its seems in the JS world the most widely used, humanly readable and naturally sortable. I'll store offsets on a per user basis.
如果一個實現有點太問了,如果有人能告訴我這兩種格式的正確名稱,我可能會更幸運地理解如何轉換.
If an implementation is again a bit much too ask, if someone can tell me the correct name for both formats I might have more luck in understanding how to convert.
推薦答案
jsonDate = "/Date(1154970000000+0700)/";
var strDate = parseInt(jsonDate.replace(//Date(([-d]+).*$/, "$1"));
var strHour = parseInt(jsonDate.replace(/.*d([+-]dd).*$/, "$1"), 10);
var strMin = parseInt(jsonDate.replace(/.*d([+-])dd(dd).*$/, "$1$2"), 10);
var date = new Date(strDate);
if (!isNaN(strHour)) date.setHours(date.getHours() + strHour);
if (!isNaN(strMin)) date.setMinutes(date.getMinutes() + strMin);
var out = date.toISOString();
以及轉換為 ISO 的函數:
And the function to convert to ISO:
var toISOString = Date.prototype.toISOString ?
function(d){return d}:
(function(){
function t(i){return i<10?"0"+i:i};
function h(i){return i.length<2?"00"+i:i.length<3?"0"+i:3<i.length?Math.round(i/Math.pow(10,i.length-3)):i};
function toISOString(){
return "".concat(
this.getUTCFullYear(), "-",
t(this.getUTCMonth() + 1), "-",
t(this.getUTCDate()), "T",
t(this.getUTCHours()), ":",
t(this.getUTCMinutes()), ":",
t(this.getUTCSeconds()), ".",
h("" + this.getUTCMilliseconds()), "Z"
);
};
return function(d){
d.toISOString = toISOString;
return d;
}
})();
這篇關于日期轉換 .NET JSON 到 ISO的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!