get Javascript date formatted as 2011-04-01

corroded picture corroded · Apr 1, 2011 · Viewed 9.7k times · Source

I've seen this: how to get formatted date time like 2009-05-29 21:55:57 using javascript?

but I do need the 0's before a single digit date(I need 2011-04-01, not 2011-4-1)

I don't like to add another unnecessary plugin for this one so if there's a builtin function or SIMPLE function in js/jquery that could do this, I'm good. I do hope it will not result to a 10 line function just to check if the month was singular and then add a zero to it.

Basically, I am using the AnyTime js (http://www.ama3.com/anytime/) plugin but it throws an error if my starting date was not in the form "yyyy-mm-dd". My starting default value is "now" so I am trying to convert a new Date() to that format. Any help?

NOTE please don't give links of plugins as i was hoping for a REALLY simple solution. i find that using a plugin just to fix a plugin isn't actually very clean.

Answer

vvk picture vvk · Apr 1, 2011
   function getFormattedDate() {
        var date = new Date();
        var str = date.getFullYear() + "-" + getFormattedPartTime(date.getMonth()) + "-" + getFormattedPartTime(date.getDate()) + " " +  getFormattedPartTime(date.getHours()) + ":" + getFormattedPartTime(date.getMinutes()) + ":" + getFormattedPartTime(date.getSeconds());

        return str;
    }

    function getFormattedPartTime(partTime){
        if (partTime<10)
           return "0"+partTime;
        return partTime;
    }