2016-08-02 79 views
-3

我正在使用jQuery。在jquery中將日期轉換爲「Y-m-d」formate

我的日期格式爲August 2, 2016格式。

現在,我想將此日期轉換爲Y-m-d格式爲2016-08-02

那麼,我應該寫什麼jQuery來解決這個問題?

+2

每一個可以想象的JavaScript日期格式的問題已經被問和在這裏回答了十幾次(在網上大量上千次)。發帖前請先搜索。 –

+0

jQuery沒有日期特定的功能,請嘗試在這裏:http://stackoverflow.com/questions/5250244/jquery-date-formatting –

+0

不是一個答案,但建議:我真的建議檢出[moment.js] (http://momentjs.com/),如果你在日期上做了很多工作。 JavaScript日期/時間可以是一個相當噩夢,moment.js使它很容易 –

回答

1

您可以使用此代碼爲年月日

var date = new Date(userDate), 
yr  = date.getFullYear(), 
month = date.getMonth(), 
day  = date.getDate(), 
newDate = yr + '-' + month + '-' + day; 
console.log(newDate); 

或本作YYYY-MM-DD

var date = new Date(userDate), 
yr  = date.getFullYear(), 
month = date.getMonth() < 10 ? '0' + date.getMonth() : date.getMonth(), 
day  = date.getDate() < 10 ? '0' + date.getDate() : date.getDate(), 
newDate = yr + '-' + month + '-' + day; 
console.log(newDate); 
0
Date.prototype.yyyymmdd = function() {   

    var yyyy = this.getFullYear().toString();          
    var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based   
    var dd = this.getDate().toString();    

    return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]); 
}; 

d = new Date(); 
$('#today').html(d.yyyymmdd()); 

check here