javascriptdateformatting

How to convert a full date to a short date in javascript?


I have a date like this Monday, January 9, 2010

I now want to convert it to

1/9/2010 mm/dd/yyyy

I tried to do this

    var startDate = "Monday, January 9, 2010";
    var convertedStartDate = new Date(startDate);
    var month = convertedStartDate.getMonth() + 1
    var day = convertedStartDate.getDay();
    var year = convertedStartDate.getFullYear();
    var shortStartDate = month + "/" + day + "/" + year;

However it must be thinking the date is in a different format since day returns 1 instead of 9.


Solution

  • The getDay() method returns a number to indicate the day in week (0=Sun, 1=Mon, ... 6=Sat). Use getDate() to return a number for the day in month:

    var day = convertedStartDate.getDate();
    

    If you like, you can try to add a custom format function to the prototype of the Date object:

    Date.prototype.formatMMDDYYYY = function(){
        return (this.getMonth() + 1) + 
        "/" +  this.getDate() +
        "/" +  this.getFullYear();
    }
    

    After doing this, you can call formatMMDDYYY() on any instance of the Date object. Of course, this is just a very specific example, and if you really need it, you can write a generic formatting function that would do this based on a formatting string, kinda like java's SimpleDateeFormat (http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html)

    (tangent: the Date object always confuses me... getYear() vs getFullYear(), getDate() vs getDay(), getDate() ranges from 1..31, but getMonth() from 0..11

    It's a mess, and I always need to take a peek. http://www.w3schools.com/jsref/jsref_obj_date.asp)