如何将JS日期时间转换为MySQL日期时间?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (219)

如何将JS dateTime转换为MySQL DateTime?另外,是否有一种方法可以将特定的分钟数添加到JS日期时间,然后将其传递给MySQL日期时间?

提问于
用户回答回答于

我的代码

/**
 * You first need to create a formatting function to pad numbers to two digits…
 **/
function twoDigits(d) {
    if(0 <= d && d < 10) return "0" + d.toString();
    if(-10 < d && d < 0) return "-0" + (-1*d).toString();
    return d.toString();
}

/**
 * …and then create the method to output the date string as desired.
 * Some people hate using prototypes this way, but if you are going
 * to apply this to more than one Date object, having it as a prototype
 * makes sense.
 **/
Date.prototype.toMysqlFormat = function() {
    return this.getUTCFullYear() + "-" + twoDigits(1 + this.getUTCMonth()) + "-" + twoDigits(this.getUTCDate()) + " " + twoDigits(this.getUTCHours()) + ":" + twoDigits(this.getUTCMinutes()) + ":" + twoDigits(this.getUTCSeconds());
};
用户回答回答于
var date;
date = new Date();
date = date.getUTCFullYear() + '-' +
    ('00' + (date.getUTCMonth()+1)).slice(-2) + '-' +
    ('00' + date.getUTCDate()).slice(-2) + ' ' + 
    ('00' + date.getUTCHours()).slice(-2) + ':' + 
    ('00' + date.getUTCMinutes()).slice(-2) + ':' + 
    ('00' + date.getUTCSeconds()).slice(-2);
console.log(date);

甚至更短:

new Date().toISOString().slice(0, 19).replace('T', ' ');

输出:

2012-06-22 05:40:06

对于更高级的用例,包括控制时区,考虑使用http://medijs.com/:

require('moment')().format('YYYY-MM-DD HH:mm:ss');

轻量级替代方案,考虑https://github.com/taylorhakes/efha

require('fecha').format('YYYY-MM-DD HH:mm:ss')

扫码关注云+社区

领取腾讯云代金券

玩转腾讯云 有奖征文活动