views:

551

answers:

1

Hi

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.

+2  A: 

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() + 
    "/" +  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)

Roland Bouman
Cool that worked. But how can I set it to always do the mm/dd/yyyy since I always want this in that date format no matter what the client set. Like I know I am printing it in the format I want but I am not sure if how it would react to the conversion if it would try to put it in the client format.
chobo2
I am still not sure if I need to be concerned about other date formats. Maybe I have to post a new question.
chobo2
`Date` is just a class for representing date/time values. It has a number of methods that return a string representation, but your desired format is simply not there. The format you created is not a `Date` object: it's a string, you just created it with data coming out of the `Date` object. You can try to add your own formatting method to the prototype of the `Date` object. I'll edit my answer to show how.
Roland Bouman