2012-11-19 30 views
41

可能重複的格式:
Format date to MM/dd/yyyy in javascript的Javascript更改日期到(DD/MM/YYYY)

我如何轉換低於下列日期格式(星期一11月19日13:29 :40 2012)

成:

日/月/年

<html> 
    <head> 
    <script type="text/javascript"> 
     function test(){ 
     var d = Date() 
     alert(d) 
     } 
    </script> 
    </head> 

<body> 
    <input onclick="test()" type="button" value="test" name="test"> 
</body> 
</html> 
+3

你有什麼試過的?它看起來並不像這段代碼試圖對日期進行任何串處理。 –

回答

120

一些JavaScript引擎,可直接解析該格式,這使得任務很簡單:

function convertDate(inputFormat) { 
    function pad(s) { return (s < 10) ? '0' + s : s; } 
    var d = new Date(inputFormat); 
    return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/'); 
} 
27

這將確保你得到一個兩位數的日,月。

function formattedDate(d = new Date) { 
    let month = String(d.getMonth() + 1); 
    let day = String(d.getDate()); 
    const year = String(d.getFullYear()); 

    if (month.length < 2) month = '0' + month; 
    if (day.length < 2) day = '0' + day; 

    return `${month}/${day}/${year}`; 
} 
+0

「這個問題以前已經問過了,已經有了答案,如果這些答案沒有完全解決你的問題,請提出一個新問題。」人確實問一個新的問題,爲什麼讓它看起來好像他們忽略了「重複」的答案。 stackoverflow應該是關於幫助人們不愚蠢的書呆子點評分和盒子滴答作響。 – 2017-12-01 15:09:31