Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/377.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将javascript转换为日期对象到mysql日期格式(YYYY-MM-DD)_Javascript_Mysql_Date - Fatal编程技术网

将javascript转换为日期对象到mysql日期格式(YYYY-MM-DD)

将javascript转换为日期对象到mysql日期格式(YYYY-MM-DD),javascript,mysql,date,Javascript,Mysql,Date,我正在尝试使用javascript将日期对象转换为有效的mysql日期-最好的方法是什么?可能最好使用一个库,如(尽管多年来没有维护过)或 但是要手动执行,可以使用Date#getFullYear(),Date#getMonth()(它从0=一月开始,所以您可能需要+1)和Date#getDate()(月日)。只需将月份和日期填充为两个字符,例如: (function() { Date.prototype.toYMD = Date_toYMD; function Date_toY

我正在尝试使用javascript将日期对象转换为有效的mysql日期-最好的方法是什么?

可能最好使用一个库,如(尽管多年来没有维护过)或

但是要手动执行,可以使用
Date#getFullYear()
Date#getMonth()
(它从0=一月开始,所以您可能需要+1)和
Date#getDate()
(月日)。只需将月份和日期填充为两个字符,例如:

(function() {
    Date.prototype.toYMD = Date_toYMD;
    function Date_toYMD() {
        var year, month, day;
        year = String(this.getFullYear());
        month = String(this.getMonth() + 1);
        if (month.length == 1) {
            month = "0" + month;
        }
        day = String(this.getDate());
        if (day.length == 1) {
            day = "0" + day;
        }
        return year + "-" + month + "-" + day;
    }
})();
用法:

var dt = new Date();
var str = dt.toYMD();
请注意,函数有一个名称,这对于调试非常有用,但由于匿名作用域函数,因此不会污染全局命名空间

使用当地时间;对于UTC,只需使用UTC版本(
getUTCFullYear
等)


警告:我刚刚把它扔掉了,它完全没有经过测试。

看看这个方便的库,可以满足您所有的日期格式需求:

在第一个示例中有点输入错误,当一天的长度小于1时,它会将月份而不是日期添加到结果中

如果你改变了,效果会很好:

    if (day.length == 1) {
        day = "0" + month;
    }

谢谢你发布这个脚本

修正后的函数如下所示:

Date.prototype.toYMD = Date_toYMD;
function Date_toYMD() {
    var year, month, day;
    year = String(this.getFullYear());
    month = String(this.getMonth() + 1);
    if (month.length == 1) {
        month = "0" + month;
    }
    day = String(this.getDate());
    if (day.length == 1) {
        day = "0" + day;
    }
    return year + "-" + month + "-" + day;
}
可以

function Date_toYMD(d)
{
    var year, month, day;
    year = String(d.getFullYear());
    month = String(d.getMonth() + 1);
    if (month.length == 1) {
        month = "0" + month;
    }
    day = String(d.getDate());
    if (day.length == 1) {
        day = "0" + day;
    }
    return year + "-" + month + "-" + day;
}
//函数
getDate=函数(dateObj){
var day=dateObj.getDay()<9?'0'+dateObj.getDay():dateObj.getDay();
var month=dateObj.getMonth()<9?'0'+dateObj.getMonth():dateObj.getMonth();
return dateObj.getFullYear()++'-'+月+'-'+日;
}
//示例用法
log(getDate(newdate());
//带定制日期
log(getDate(新日期(2012,dateObj.getMonth()-30,dateObj.getDay());

这对我有效,只需编辑字符串即可:

var myDate = new Date();
var myDate_string = myDate.toISOString();
var myDate_string = myDate_string.replace("T"," ");
var myDate_string = myDate_string.substring(0, myDate_string.length - 5);
约会

new Date().toJSON().slice(0, 10)
//2015-07-23
日期时间

new Date().toJSON().slice(0, 19).replace('T', ' ')
//2015-07-23 11:26:00
请注意,生成的日期/日期时间将始终在UTC时区中

以下各项的最短版本:

使用:

var date = mysqlDate(); //'2014-12-05'
仅此而已:

Object.defineProperties( Date.prototype ,{
    date:{
         get:function(){return this.toISOString().split('T')[0];}
    },
    time:{
         get:function(){return this.toTimeString().match(/\d{2}:\d{2}:\d{2}/)[0];}
    },
    datetime:{
         get : function(){return this.date+" "+this.time}
    }
});
现在你可以使用

sql_query = "...." + (new Date).datetime + "....";

我需要这个文件名和当前时区的时间

const timezoneOffset = (new Date()).getTimezoneOffset() * 60000;

const date = (new Date(Date.now() - timezoneOffset))
    .toISOString()
    .substring(0, 19)
    .replace('T', '')       // replace T with a space
    .replace(/ /g, "_")     // replace spaces with an underscore
    .replace(/\:/g, ".");   // replace colons with a dot
来源

从JS日期到Mysql日期格式转换,您只需执行以下操作:

date.toISOString().split("T")[0]
试试这个

dateTimeToMYSQL(datx) {
    var d = new Date(datx),
      month = '' + (d.getMonth() + 1),
      day = d.getDate().toString(),
      year = d.getFullYear(),
      hours = d.getHours().toString(),
      minutes = d.getMinutes().toString(),
      secs = d.getSeconds().toString();
    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;
    if (hours.length < 2) hours = '0' + hours;
    if (minutes.length < 2) minutes = '0' + minutes;
    if (secs.length < 2) secs = '0' + secs;
    return [year, month, day].join('-') + ' ' + [hours, minutes, secs].join(':');
  }
dateTimeToMYSQL(datx){
var d=新日期(datx),
月份=“”+(d.getMonth()+1),
day=d.getDate().toString(),
year=d.getFullYear(),
小时数=d.getHours().toString(),
分钟数=d.getMinutes().toString(),
secs=d.getSeconds().toString();
如果(月长<2)月='0'+月;
如果(日长<2)天='0'+天;
如果(小时长度<2)小时='0'+小时;
如果(分钟长度<2)分钟='0'+分钟;
如果(秒长度<2)秒='0'+秒;
return[year,month,day]。加入('-')+'+[hours,minutes,secs]。加入(':');
}
请注意,您可以删除小时、分钟和秒,结果为YYYY-MM-DD 优点是在HTML表单中输入的日期时间保持不变:不转换为UTC

结果将是(以您为例):

dateToMYSQL(datx){
var d=新日期(datx),
月份=“”+(d.getMonth()+1),
day=d.getDate().toString(),
year=d.getFullYear();
如果(月长<2)月='0'+月;
如果(日长<2)天='0'+天;
返回[年、月、日]。加入('-');
}

我想说的是,这可能是最好的解决方法。刚刚确认它有效:

new Date().toISOString().replace('T', ' ').split('Z')[0];

这里有很多错误。不要重新声明
var
。阅读“提升”。此外,这就足够了,
new Date().toISOString().slice(0,10)
@Gajus for me
Date().toISOString().slice(0,10)
不够多个日期失败-1979年6月7日错误1天,例如-1当您使用
toISOString()时
您正在将显示的时区的日期转换为UTC时间。例如,如果您正在查看的网页位于GMT-6并显示GMT-6时间,并且您的浏览器运行在GMT-5计算机上,则当您使用
toISOString()时
现在,您将拥有一个UTC时间,该时间为网页5小时,而不是6小时。OP的可能副本需要一个MySQL日期对象,而不是日期时间,因此您需要“/T.*/”而不是“'T”“。除此之外,您还想知道为什么这不是最受欢迎的答案?为什么不是这个?(new DATE()).toISOString()。子字符串(0,10)请注意,在9999;)之后的几年内,这将不起作用(新日期(str_Date)).toISOString().substring(0,10)日期变为str_日期之前的一天。从字符串解析为字符串时不准确date@KubaHoluj我将确保在评论中为穷人添加一条关于这一点的注释,他们将在10000年审查我的代码
const timezoneOffset = (new Date()).getTimezoneOffset() * 60000;

const date = (new Date(Date.now() - timezoneOffset))
    .toISOString()
    .substring(0, 19)
    .replace('T', '')       // replace T with a space
    .replace(/ /g, "_")     // replace spaces with an underscore
    .replace(/\:/g, ".");   // replace colons with a dot
date.toISOString().split("T")[0]
dateTimeToMYSQL(datx) {
    var d = new Date(datx),
      month = '' + (d.getMonth() + 1),
      day = d.getDate().toString(),
      year = d.getFullYear(),
      hours = d.getHours().toString(),
      minutes = d.getMinutes().toString(),
      secs = d.getSeconds().toString();
    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;
    if (hours.length < 2) hours = '0' + hours;
    if (minutes.length < 2) minutes = '0' + minutes;
    if (secs.length < 2) secs = '0' + secs;
    return [year, month, day].join('-') + ' ' + [hours, minutes, secs].join(':');
  }
dateToMYSQL(datx) {
    var d = new Date(datx),
      month = '' + (d.getMonth() + 1),
      day = d.getDate().toString(),
      year = d.getFullYear();
    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;
    return [year, month, day].join('-');
  }
new Date().toISOString().replace('T', ' ').split('Z')[0];