有人知道如何将JS datetime转换为MySQL dateTime吗?另外,有没有一种方法可以将特定的分钟数添加到JS datetime,然后将其传递给MySQL datetime?
发布于 2011-02-27 22:44:23
虽然JS确实拥有足够的基本工具来完成这项工作,但它相当笨拙。
/**
* 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());
};发布于 2012-06-22 13:40:51
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://momentjs.com/
require('moment')().format('YYYY-MM-DD HH:mm:ss');对于momentjs的轻量级替代方案,可以考虑使用https://github.com/taylorhakes/fecha
require('fecha').format('YYYY-MM-DD HH:mm:ss')发布于 2017-06-30 01:53:11
我认为使用toISOString()方法可以使解决方案变得不那么笨拙,它具有广泛的浏览器兼容性。
所以你的表达式将是一行代码:
new Date().toISOString().slice(0, 19).replace('T', ' ');生成的输出:
"2017-06-29 17:54:04"
https://stackoverflow.com/questions/5129624
复制相似问题