Satch3000
Satch3000

Reputation: 49364

Change date format (Javascript)

I have this code:

var fd=1+self.theDate.getMonth() +'/'+ today+'/'+self.theDate.getFullYear();

It works, but it's format is Month, Day, Year.

I need to change it to: Day, Month Year.

So, I tried this:

var fd=1+today +'/'+ self.theDate.getMonth()+'/'+self.theDate.getFullYear();

Now, my change does not work. Is it that I have not done it properly or is my change right?

Thanks

Upvotes: 0

Views: 1364

Answers (3)

Adam Bergmark
Adam Bergmark

Reputation: 7536

You are no longer adding 1 to the month, you are adding it to today. Make sure to parenthesize this since "x" + 1 + 2 => "x12" but "x" + (1 + 2) => "x3"

Upvotes: 1

mplungjan
mplungjan

Reputation: 177685

var theDate = new Date();
var today = theDate.getDate();
var month = theDate.getMonth()+1; // js months are 0 based
var year = theDate.getFullYear();
var fd=today +'/'+ month +'/'+year

or perhaps you prefer 22/05/2011

var theDate = new Date();
var today = theDate.getDate();
if (today<10) today="0"+today;
var month = theDate.getMonth()+1; // js months are 0 based
if (month < 10) month = "0"+month;
var year = theDate.getFullYear();
var fd=""+today +"/"+ month +"/"+year

Upvotes: 1

John Green
John Green

Reputation: 13435

I expect the correct answer is this:

var fd=today +'/'+ (self.theDate.getMonth() + 1) +'/'+self.theDate.getFullYear();

This leaves today alone, and groups Month so that it does a proper number addition instead of string concatenation.

Upvotes: 1

Related Questions