2012-02-04 77 views
4

我有一個函數發送ajax請求到服務器文件的參數。問題是我想發送當前日期時間值來比較它從數據庫。任何Javascript日期時間函數返回MySQL日期時間格式?

作爲MySQL數據時間格式所有日期時間顯示爲「2012-02-03 19:50:28」格式。

我怎樣才能在Javascript中生成它。

另一個問題是:我可以添加小時到當前日期時間(修復服務器時區的問題)

在此先感謝

回答

9

試試這個

/* use a function for the exact format desired... */ 
function ISODateString(d){ 
    function pad(n){return n<10 ? '0'+n : n} 
    return d.getUTCFullYear()+'-' 
     + pad(d.getUTCMonth()+1)+'-' 
     + pad(d.getUTCDate()) +' ' 
     + pad(d.getUTCHours())+':' 
     + pad(d.getUTCMinutes())+':' 
     + pad(d.getUTCSeconds()) 
} 

var d = new Date(); 
console.log(ISODateString(d)); // prints something like 2009-09-28 19:03:12 

Refernece:
date format
date type in javascript
working with dates

+0

它非常好。謝謝 – 2012-02-04 06:59:49

1

解析日期到您的格式字符串,您可以通過Date API或使用Datejs(一個強大的日期插件)。

但我建議你推毫秒數服務器/ MySQL的,而不是字符串:

new Date().getTime(); 
4

試試這個:

Date.prototype.toMysqlFormat = function() { 
    function pad(n) { return n < 10 ? '0' + n : n } 
    return this.getFullYear() + "-" + pad(1 + this.getMonth()) + "-" + pad(this.getDate()) + " " + pad(this.getHours()) + ":" + pad(this.getMinutes()) + ":" + pad(this.getSeconds()); 
}; 
var TimeNow = new Date().toMysqlFormat(); 
alert(TimeNow); //Alerts Current TimeStamp