Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams OP wants a MySQL DATE object, not a DATETIME, so you need "/T.*/" instead of "'T'". apart from that, wondering why this is not the most upvoted answer? xShirase Sep 13, 2014 at 17:15 When i did this (new Date(str_date)).toISOString().substring(0, 10) the date became day before the str_date. not accurate when parsing from string to date Shift 'n Tab Nov 7, 2017 at 23:41 @KubaHoluj I'll make sure to add a note about that in the comments for the poor sod reviewing my code in the year 10000 serakfalcon Mar 12, 2018 at 5:44

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.

MomentJS also now "a legacy project" in their own words momentjs.com/docs/#/-project-status so best is actually to directly use Date. – Jim Driscoll Dec 28, 2021 at 11:12
const date = new Date();
const myDate = date.toISOString().replace("T", " ");
const myDateString = myDate.substring(0, myDate.length - 5);
console.log(myDateString);
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 1, 2013 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, 2014 at 1:45 -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, 2014 at 15:47

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

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

  • convert-javascript-to-date-object-to-mysql-date-format-yyyy-mm-dd
  • javascript-toisostring-ignores-timezone-offset
  • 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];
    
    // 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()));
          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('-');
            

    Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.