John
John

Reputation: 23

getting two different date months

I'm a newbie trying to learn JavaScript through a video course on Lynda.com The instructor started with the alert() code to make what we wrote show up in an alert box. And then he showed about writing code to come back with today's date in an alert box:

var date = new Date();
alert("Today's date is " + date); 

I am including this to show that the date variable was set for the current date.

Next thing was making what we wrote appear on the actual web page section, at the top of the open document.

document.body.innerHTML = "<h1>The date today is " + date + "<h1>"

And it came back with the same date, June 15 only, this time in the web page itself.

This next part is where I got a different month, despite putting in exactly what I was supposed to. To make it more readable, we're told about the get function to grab specific pieces of information.

document.body.innerHTML = "<h1>The date today is " + date.getMonth() + "/" + date.getDate() + "/" + date.getFullYear() + "</h1>"

and it comes back with:

The date today is 5/15/2018

I can't figure out why it's telling me it's May 15, 2018 while earlier the date was correct. I can't figure out where my code is wrong. Any help that can be given would be appreciated.

Upvotes: 2

Views: 76

Answers (2)

UkFLSUI
UkFLSUI

Reputation: 5672

The javascript getMonth() method returns the month (from 0 to 11) for the specified date, according to local time. That means, January is 0, February is 1, and so on. So, current month (June) returned 5 in your output.

To get the desired output in your code, correct it like below:

var date = new Date();
document.body.innerHTML = "<h1>The date today is " +  (parseInt(date.getMonth(), 10) + 1) + "/" + date.getDate() + "/" + date.getFullYear() + "</h1>";

Upvotes: 0

Brett Commandeur
Brett Commandeur

Reputation: 590

This is intended as the returned month is zero-based so June is indeed month 5.

From the date.getMonth() docs on MDN:

The getMonth() method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth

Upvotes: 1

Related Questions