54

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

double-beep
  • 5,031
  • 17
  • 33
  • 41
BrynJ
  • 8,322
  • 14
  • 65
  • 89
  • 1
    possible duplicate of [Convert JS date time to MySQL datetime](http://stackoverflow.com/questions/5129624/convert-js-date-time-to-mysql-datetime) – Gajus Dec 01 '13 at 12:01

14 Answers14

160

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.

Afanasii Kurakin
  • 3,330
  • 2
  • 24
  • 26
32

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
11

The shortest version of this answer by Chris Mayhew:

/**
 * MySQL date
 * @param {Date} [date] Optional date object
 * @returns {string}
 */
function mysqlDate(date = new Date()) {
  return date.toISOString().split('T')[0];
}

const date = mysqlDate();
console.log(date);
double-beep
  • 5,031
  • 17
  • 33
  • 41
Vitaly Sivkov
  • 407
  • 8
  • 14
8

Just edit the string instead:

const date = new Date();
const myDate = date.toISOString().replace("T", " ");
const myDateString = myDate.substring(0, myDate.length - 5);

console.log(myDateString);
double-beep
  • 5,031
  • 17
  • 33
  • 41
Chris Mayhew
  • 97
  • 1
  • 1
  • 4
    There are quite a few things wrong here. Do not redeclare `var`. Read about "hoisting". Furthermore, this is sufficient, `new Date().toISOString().slice(0, 10)`. – Gajus Dec 01 '13 at 12:00
  • @Gajus for me `Date().toISOString().slice(0, 10)` was not sufficient fails with several dates - wrong by 1 day for 7th June 1979 for instance – Tin Bum Mar 10 '14 at 01:45
  • 1
    -1 when you use `toISOString()` you are converting the date from the timezone shown into UTC time. So for example if the web page you are looking at is on GMT-6 and showing a GMT-6 time and your browser is running on a computer that is GMT-5 then when you use `toISOString()` you will now have a UTC time that 5 hours off the webpage instead of 6 – gillyspy Jul 22 '14 at 15:47
7

function js2Sql(cDate) {
    return cDate.getFullYear()
         + '-'
         + ("0" + (cDate.getMonth() + 1)).slice(-2)
         + '-'
         + ("0" + cDate.getDate()).slice(-2);
}

const currentDate = new Date();
const sqlDate = js2Sql(currentDate);

console.log(sqlDate);
double-beep
  • 5,031
  • 17
  • 33
  • 41
KMT
  • 71
  • 1
  • 1
6

To convert a JavaScript date to a MySQL one, you can do:

const currentDate = new Date();
const date = currentDate.toISOString().split("T")[0];

console.log(date);
double-beep
  • 5,031
  • 17
  • 33
  • 41
Jan Jůna
  • 4,965
  • 3
  • 21
  • 27
3

A bit of a typo in the first example, when a day has a length less than 1 it is adding the month instead of the day to the result.

Works great though if you change:

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

to

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

Thanks for posting that script.

The corrected function looks like:

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;
}
salonMonsters
  • 1,237
  • 3
  • 16
  • 26
3

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

const date = (new Date).datetime
console.log(date);
double-beep
  • 5,031
  • 17
  • 33
  • 41
bortunac
  • 4,642
  • 1
  • 32
  • 21
2

I needed this for a filename and with the time in the current timezone.

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

Source

Community
  • 1
  • 1
blablabla
  • 1,468
  • 15
  • 17
1

I'd like to say that this is likely the best way of going about it. Just confirmed that it works:

new Date().toISOString().replace('T', ' ').split('Z')[0];
Bennybear
  • 335
  • 2
  • 13
0
// function
getDate = function(dateObj){
    var day = dateObj.getDay() < 9 ? '0'+dateObj.getDay():dateObj.getDay();
    var month = dateObj.getMonth() < 9 ? '0'+dateObj.getMonth():dateObj.getMonth();
    return dateObj.getFullYear()+'-'+month+'-'+day;
}

// example usage
console.log(getDate(new Date()));

// with custom date
console.log(getDate(new Date(2012,dateObj.getMonth()-30,dateObj.getDay()));
cnizzardini
  • 1,196
  • 1
  • 13
  • 29
0

Take a look at this handy library for all your date formatting needs: http://blog.stevenlevithan.com/archives/date-time-format

JoseMarmolejos
  • 1,760
  • 1
  • 17
  • 34
0

Try this

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

Note that you can remove the hours, minutes and seconds and you will have the result as YYYY-MM-DD The advantage is that the datetime entered in the HTML form remains the same: no transformation into UTC

The result will be (for your example) :

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('-');
  }
avimimoun
  • 799
  • 9
  • 23
0

Can be!

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;
}
Jason Sturges
  • 15,855
  • 14
  • 59
  • 80