20

Using the javascript code below I get month = 3, day = 5, y = 2014. Of course I expect month 4 and day 18.

var TodayDate = new Date();
var d = TodayDate.getDay();
var m = TodayDate.getMonth();
var y = TodayDate.getFullYear();

What am I doing wrong?

2
  • This is not jQuery code, but only Javascript. See Date javascript documentation. Commented Apr 18, 2014 at 20:01
  • @VincentDecaux I didn't notice that I was using JavaScript and not jQuery. Would jQuery be better/faster? And if so, what jQuery function should it be? Thank you for catching my mistake. Commented Apr 18, 2014 at 20:17

2 Answers 2

34

you have to use getMonth() + 1 to get month (zero-index based) because javascript implementation followed JAVA & that is how java.util.Date did it.

getDay() - gives you 5 for today being Friday(6th Day of the week. Sunday 0 to Saturday 6)

getDate() - gives you 18 (today's date)

Sign up to request clarification or add additional context in comments.

4 Comments

Krishna, thank you. What about .getDay() why is it not correct?
I have a tough time deciding to whom I should give the Answer since both answered at the same time :)
@Hidalgo - Haha.. I will leave that to you, although I must say I answered a few seconds before Praveen did. I rest my case. I won't hold it against you if you accepted his answer though ;)
Thank you very much for explanation about getMonth() as zero-index based.
7

it is getDate() not getDay()

var d = TodayDate.getDate();  //it returns the date 
var m = TodayDate.getMonth()+1; //returns the index of the month array
                                //for our convenience we add 1 to it

month in Date object is an array which starts with 0 -11 (Jan starting with 0 and dec ends with 11)

FYI:

getDay() - returns the day(ie, friday in number as 5 ) => Sun starts with 0 and Sat ends with 6 [Again it is an array]

1 Comment

TodayDate is not defined!! like var TodayDate = new Date();

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.