2016-03-28 152 views
0

我從服務器獲取日期爲字符串的數組,現在我只想過濾日,月和年。如何將過濾結果格式化爲特定的日期格式?將日期字符串轉換爲Javascript中的正確日期

var date = ['2015-02-04T23:54:00.000+01:00','2015-02-04T23:54:00.000+01:00', ...]; 

//wanted result: 2015-02-04 or 04.02.2015 
+2

如何使用'新的日期(STRING);'循環?然後,'dateObj.getMonth()','dateObj.getFullYear()'... – Rayon

+0

你可以使用這個時刻 –

回答

1

你可以轉換你的什麼的看起來是一個ISO日期格式是這樣的:

var date = ['2015-02-04T23:54:00.000+01:00','2015-02-04T23:54:00.000+01:00']; 

date.map(function(_d) { 
    var d = new Date(_d) 
    return d.getFullYear() + '-' + d.getMonth() + 1 + '-' + d.getDay() 
} 

// if you want to get fancy, you could throw in this function to pad the days and months: 
var pad = function (n) {return n<10? '0'+n:''+n;} 

var sorted = date.map(function(_d) { 
    var d = new Date(_d) 
    return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDay()) 
}) 
console.log(sorted); 
+0

您可以嘗試'return d.toISOString()。split('T ')[0]' – Rajesh

+0

如果我使用你的建議,這裏是我所獲得的:'2015-02-04'。用我的,我有'2015-02-03'。你如何處理時區部分('T23:54:00.000 + 01:00')? – cl3m

+0

它對我來說工作得很好:[JSFiddle](https://jsfiddle.net/RajeshDixit/0o1otxho/)。我嘗試了幾個時區,但不確定。 – Rajesh

0

如果你提到的格式是一致的,那麼:

date.forEach(function(d) { 
    d = d.substring(0, 10); 
}) 
+1

在大多數情況下工作,但如果日期是'2015-2-4T23:54: 00.000 + 01:00'? – Rayon

+2

正如我所說,如果格式是一致的。如果格式不一致,那麼我認爲沒有任何跨瀏覽器兼容解決方案。在將字符串轉換爲日期的情況下,即使'新日期'的實現也不一致。 –

1

日期可以接受字符串的參數。使用for循環遍歷列表,然後爲每個列表創建一個新的Date對象。

var date = ['2015-02-04T23:54:00.000+01:00','2015-02-04T23:54:00.000+01:00'] 
var dateObjects = []; 

for (var i = 0; i<date.length; i++) { 
    d = new Date(date[i]); 
    dateObjects.push(d); 
} 

或者,在一個單行:

var dateObjects = date.map(function (datestr) {return new Date(datestr)}); 

現在,你可以發現,月,日,並通過以下方法其中之一年:

var year = dateObjects[0].getFullYear(); // Gets the year 
var month = dateObjects[0].getMonth()+1; // Gets the month (add 1 because it's zero-based) 
var day = dateObjects[0].getDate(); // Gets the day of the month 

dateObjects[0]僅僅是一個引用列表中第一個日期的例子。

那麼你就可以得到你的輸出字符串如

var dateStrings = dateObjects.map(function (item) { 
    return item.getFullYear()+"-"+(item.getMonth()+1)+"-"+item.getDate(); 
}) 
+1

你可以嘗試'Array.map'。 'var dateObj = date.map(function(item){return new Date(item);});' – Rajesh

+0

@Rajesh感謝您指出這一點;) –

1
var date = ['2015-02-04T23:54:00.000+01:00','2015-02-04T23:54:00.000+01:00']; 
var newdateobject = []; 

$.each(date, function(key, e) { 
var a = new Date(e); 
    newdateobject.push(a.getFullYear()+'-'+(a.getMonth()+1) +'-'+a.getDate()); 
});