0

I am having trouble understanding why a Date in Javascript come out wrong. For example...

$scope.campaign.date_start = new Date(19/11/2014);
Wed Nov 19 2014 00:00:00 GMT+0000 (GMT) - correct
$scope.campaign.date_start.getDay() = 19 - correct

So far so good, however getting the Month and the year gives me incorrect values....

$scope.campaign.date_start.getMonth() = 10 - incorrect should be 11
$scope.campaign.date_start.getYear() = 114 incorrect should be 2014

What I'm I going wrong here?

3
  • 2
    The months and day of the week are indexed at 0 Commented Nov 6, 2014 at 16:15
  • They are not giving you incorrect values. See the docs. getMonth(): Returns the month (0-11) getYear(): Returns the year minus 1900 Commented Nov 6, 2014 at 16:16
  • The real question is: "What didn't you do?". You did not read the proverbial manual. Commented Nov 6, 2014 at 16:26

4 Answers 4

4

JavaScript getMonth() will always return actual month-1. For the year, you will need to use getFullYear() to get the 4 digit year

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

Comments

4

getMonth is 0 based, so you need to +1 to get the number of the current month.

getYear is deprecated, and may break at some point in future, it (generally) returns the number of years since 1900. The correct method to use is getFullYear

Comments

1

Date.getMonth() is 0-base (January is month 0).

Date.getYear() is deprecated and is years since 1900 (hence 114).

http://www.w3schools.com/jsref/jsref_obj_date.asp

2 Comments

getYear() is not 0 base, it based of a 1900, so 2014-1900 so he's getting 114
Good point. Corrected. That's what I get for typing quickly and carelessly.
1

getMonth() is zero-based. So you will need getMonth()+1

getYear() was not Y2K compliant, so a new function getFullYear() was created to return 4-digit years.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.