Prometheus
Prometheus

Reputation: 33585

Incorrect Date Format in JavaScript using getMonth() and getYear()

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?

Upvotes: 0

Views: 229

Answers (4)

PM 77-1
PM 77-1

Reputation: 13334

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.

Upvotes: 1

James Thorpe
James Thorpe

Reputation: 32192

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

Upvotes: 4

Jay Dansand
Jay Dansand

Reputation: 779

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

Upvotes: 1

T.V.
T.V.

Reputation: 495

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

Upvotes: 4

Related Questions