Any Javascript DateTime Function return MySQL datetime format?

杀马特。学长 韩版系。学妹 提交于 2019-12-22 08:34:14

问题


I've a function that send ajax request to a server file with parameters. Problem is i want to send current DateTime value to compare it from database.

as MySQL datatime format all datetimes are shown as "2012-02-03 19:50:28" format.

How can i generate it in Javascript.

Another question: Can i add hours to current datetime (to fix server time zone problem)

Thanks in advance


回答1:


try this

/* 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




回答2:


Try this:

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



回答3:


Parse date to your format string, you can do it by the Date API or use Datejs (a powerful date plugin).

But I recommend you push millisecond number to server/mysql instead of string :

new Date().getTime();


来源:https://stackoverflow.com/questions/9138820/any-javascript-datetime-function-return-mysql-datetime-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!