Reputation: 1307
I want to convert date in string to date object in javascript so that I could insert it in mysql database as DATETIME.
I try new Date(date)
as work fine here, but in my js code it didn't work fine.
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?
Upvotes: 0
Views: 2251
Reputation: 4819
From here: Get String in YYYYMMDD format from JS date object?
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:
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.
Upvotes: 2