简体   繁体   English

将字符串中的日期转换为日期对象以插入数据库

[英]Convert date in string to date object for inserting in database

I want to convert date in string to date object in javascript so that I could insert it in mysql database as DATETIME. 我想将字符串中的日期转换为javascript中的日期对象,以便将其作为DATETIME插入到mysql数据库中。

I try new Date(date) as work fine here , but in my js code it didn't work fine. 在这里尝试new Date(date)可以正常工作,但是在我的js代码中,它不能正常工作。

here is the code: 这是代码:

str = "Sun Sep 06 2015 11:56:23 GMT+04:30"
new Date(str);

and here is the result : 结果如下:

2015-09-06T11:56:23.000Z 

which is different from result in here 这与这里的结果不同

and also I get following error when inserting it in database. 并且在将其插入数据库时​​出现以下错误。

Incorrect datetime value: '2015-09-06T11:56:23.000Z' for column 'start_date' at row 1

So how can I convert date? 那么如何转换日期?

From here: Get String in YYYYMMDD format from JS date object? 从这里: 从JS日期对象获取YYYYMMDD格式的字符串?

Date.prototype.yyyymmdd = function() {
    var yyyy = this.getFullYear().toString();
    var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
    var dd  = this.getDate().toString();
    return yyyy + "-" + (mm[1]?mm:"0"+mm[0]) + "-" + (dd[1]?dd:"0"+dd[0]); // padding
};

Then you can: 那么你也能:

str = "Sun Sep 06 2015 11:56:23 GMT+04:30"
new Date(str).yyyymmdd(); //returns "2015-09-06"

We can make some modifications in the original function to incorporate the time as well: 我们可以对原始函数进行一些修改以同时包含时间

Final JavaScript 最终的JavaScript

Date.prototype.YYYYMMDDhhmmss = function() {
    var YYYY = this.getFullYear().toString(),
        MM = (this.getMonth()+1).toString(),
        DD  = this.getDate().toString(),
        hh = this.getUTCHours().toString(),
        mm = this.getUTCMinutes().toString(),
        ss = this.getUTCSeconds().toString();
    return YYYY + "-" + (MM[1]?MM:"0"+MM[0]) + "-" + (DD[1]?DD:"0"+DD[0]) + " " + (hh[1]?hh:"0"+hh[0]) + ":" + (mm[1]?mm:"0"+mm[0]) + ":" + (ss[1]?ss:"0"+ss[0]);
};

Then: 然后:

str = "Sun Sep 06 2015 11:56:23 GMT+04:30"
new Date(str).YYYYMMDDhhmmss(); //returns "2015-09-06 07:26:23"

Either like this YYYY-MM-DD hh:mm:ss or YYYY-MM-DD is fine for a DateTime input in database. YYYY-MM-DD hh:mm:ssYYYY-MM-DD都适合在数据库中输入DateTime

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM