2014-08-29 48 views
-1

如何將這種類型的日期文字解析爲JavaScript中的Date對象?在JavaScript中解析日期文字

var jsonDateFromServer="/Date(1333656000000+0400)/"; 

注意,Date.parse方法不在這裏工作

+1

這不是重複的另一個問題,我們如何可以將其轉換爲Date對象? – 2014-08-29 13:27:01

+0

預期產量是多少? – 2014-08-29 13:42:51

回答

0

您可以創建一個函數,並嘗試這樣的:

function myDate(yourDateString) 
{ 
    return new Date(parseInt(yourDateString.replace('/Date(', ''))); 
} 

JSFIDDLE DEMO

+0

你沒有處理時區。 – 2014-08-29 13:40:30

+1

@Ja͢ck: - 是的,因爲沒有被問到;) – 2014-08-29 13:41:13

+0

不知道預期的結果,你怎麼知道這一點? – 2014-08-29 14:02:40

1

這是一個時間戳時區偏移。快速和骯髒的解決方案:

var jsonDateFromServer="/Date(1333656000000+0400)/"; 
// Remove the markup 
var timestamp = jsonDateFromServer.replace("/Date(", "").replace(")/", ""); 
// Parse the base timestamp first, convert it to a notation where we can add the offset easily, parse the result 
var date = new Date(new Date(parseInt(timestamp.slice(0,-5))).toUTCString() + timestamp.slice(-5));