Federico Secco Federico Secco - 2 months ago 8
Javascript Question

JavaScript function date.getMonth() not retrieving the correct month number? (11 instead of 8)

So first of all this is not about getMonth returning numbers from 0-11 instead of 1-12, and sorry for my english.

I wanted to make a simple program to display the current date on the browser, like "September is the month, 26 is the day, 2016 is the year". I did this:

!DOCTYPE HTML>
<html>
<body>
<p id="test"></p> // this is where date will be displayed
<script>
var date = new Date(); // i get the date
var m = date.getMonth(); // i get the month
var fm; // all this is to convert number to month name
if (m=0){fm="January";}
if (m=1){fm="February";}
if (m=2){fm="March";}
if (m=3){fm="April";}
if (m=4){fm="May";}
if (m=5){fm="Jun";}
if (m=6){fm="July";}
if (m=7){fm="August";}
if (m=8){fm="September";}
if (m=9){fm="October";}
if (m=10){fm="November";}
if (m=11){fm="December";}
else {fm="Error01"}
var d = date.getDate(); // the day
var y = date.getFullYear();
//document.getElementById("test").innerHTML= fm + " is the month, " + d + " is the Date(day) and "+ y + " is the full year";
// i removed this ^ to highlight the new output below:
document.getElementById("test").innerHTML= date + "<br>" + m + " - " + fm;
</script>
</body>
</html>


At This point the output should be:


Mon Sep 26 2016 23:38:39 GMT+0200 (ora legale Europa occidentale)

8 - September


("Ora legale Europa occidentale" = my local time, it shouldn't be relevant here).

But for some reasons, this is what i get when i run the program:


Mon Sep 26 2016 23:38:39 GMT+0200 (ora legale Europa occidentale)

11 - December


Month is correct in the date (says "Sept"), but wrong in the other output (m="11" which causes var fm to be "December")
Why?? :(

Answer

You should use == not =; = is assigning and == is comparing.

However, you can make your code more elegant by using an array to map the month names.

 <script>
            var date = new Date();      // i get the date 
            var m = date.getMonth();    // i get the month
            var monthMap = ["January", "Febrauary", "Mar..", "Apr..", "May", "June", "July", "Aug..", "Sept", "Oct", "Nov", "Dec"];
            var d = date.getDate();      // the day
            var y = date.getFullYear();
            //document.getElementById("test").innerHTML= monthMap[m] + " is the month, " + d + " is the Date(day) and "+ y + " is the full year"; 
            // i removed this ^ to highlight the new output below:
            document.getElementById("test").innerHTML= date + "<br>" + m + " - " + monthMap[m];
        </script>

Replace Aug... with August and other necessary month names