Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert javascript to date object to mysql date format (YYYY-MM-DD)

I'm trying to use JavaScript to convert a date object into a valid MySQL date - what is the best way to do this?

like image 886
BrynJ Avatar asked Feb 17 '10 11:02

BrynJ


2 Answers

To get the date:

const date = new Date().toJSON().slice(0, 10) console.log(date) //2015-07-23

For datetime:

const datetime = new Date().toJSON().slice(0, 19).replace('T', ' ') console.log(datetime) //2015-07-23 11:26:00

Note that the resulting date/datetime will always be in the UTC timezone.

like image 95
Afanasii Kurakin Avatar answered Sep 22 '22 03:09

Afanasii Kurakin


Update: Here in 2021, Date.js hasn't been maintained in years and is not recommended, and Moment.js is in "maintenance only" mode. We have the built-in Intl.DateTimeFormat, Intl.RelativeTimeFormat, and (soon) Temporal instead, probably best to use those. Some useful links are linked from Moment's page on entering maintenance mode.


Old Answer:

Probably best to use a library like Date.js (although that hasn't been maintained in years) or Moment.js.

But to do it manually, you can use Date#getFullYear(), Date#getMonth() (it starts with 0 = January, so you probably want + 1), and Date#getDate() (day of month). Just pad out the month and day to two characters, e.g.:

(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;     } })(); 

Usage:

var dt = new Date(); var str = dt.toYMD(); 

Note that the function has a name, which is useful for debugging purposes, but because of the anonymous scoping function there's no pollution of the global namespace.

That uses local time; for UTC, just use the UTC versions (getUTCFullYear, etc.).

Caveat: I just threw that out, it's completely untested.

like image 35
T.J. Crowder Avatar answered Sep 20 '22 03:09

T.J. Crowder