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:
Final 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…