2014-10-30 31 views
0

嗨,我想將json日期轉換回正常的dd/mm/yy日期。將json結果轉換爲適當的日期 - javascript

我怎麼能轉換Customer.DateOfBirth DD/MM/YY從一個JSON日期回正常日期?

在這裏我的代碼?

// parse the date 
       var Birth = Customer.DateOfBirth; 
       if (Birth != '') { 
        // get the javascript date object 
        Birth = DateFromString(Birth, 'dd/MM/yyyy'); 
        if (Birth == 'Invalid Date') { 
         Birth = null 
        } 
        else { 
         // get a json date 
         Birth = DateToString(Birth); 
         //REPLACE JSON DATE HERE WITH NORMAL DATE?? 
        } 
       } 

任何建議將是偉大的。 感謝

+0

那麼什麼是問題嗎? – hindmost 2014-10-30 10:22:47

+0

'Birth'變量的格式是什麼,'DateFromString'和'DateFromString'函數做了什麼? – 2014-10-30 10:22:59

+0

customer.DateOfBirth是dd/mm/yy ..我的問題是它保存爲json日期,現在我需要轉換它。我不知道我會如何去做.. – 2014-10-30 10:25:07

回答

0

如果你可以改變JSON表示要yyyy/mm/dd那麼你可以使用

Birth = new Date(Birth); 

直接轉換它,如果你必須使用目前的格式,那麼你必須做一些手工解析

提取日/月/年部件和預期的格式創建一個字符串

var parts = Birth.split('/'), 
    day = parts[0], 
    month = parts[1], 
    year = parts[2],// you need to find a way to add the "19" or "20" at the beginning of this since the year must be full for the parser. 
    fixedDate = year + '/' + month + '/' + day; 

Birth = new Date(fixedDate); 
0

您可以創建一個從mm/dd/yyyy字符串對象,因此,如果您的字符串命令dd/mm/yyyy你要麼得到Invalid Date錯誤,或者可能更糟的是,創建一個錯誤的日期(Januray 10日,而不是10月1日)的Date對象。

所以你需要將它傳遞給Date構造之前互換ddmm部分的字符串:

var datestr = Customer.DateOfBirth.replace(/(\d+)\/(\d+)\/(\d+)/,"$2/$1/$3"); 
Birth = new Date(datestr); 

你也可以傳遞一個字符串yyyy/mm/dd順序:

var datestr = Customer.DateOfBirth.split('/').reverse().join('/'); 
Birth = new Date(datestr);