views:

820

answers:

3

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

+1  A: 

Probably best to use a library like Date.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" + month;
        }
        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  A: 

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

JoseMarmolejos
+1  A: 

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