0

I have implemented a simple javascript code which displays the date on a page of mine. The thing is, it is set 1 month back. Today (25/12) it shows 25/11. Can you help me find the problem, cause I still have very basic understanding of JS and created this script following a tutorial. Thanks.

<script>
function renderDate() {
    var today = new Date();
    var d = today.getDate();
    var m = today.getMonth();
    var y = today.getFullYear();
    d = checkTime(d);
    m = checkTime(m);
    document.getElementById('dateid').innerHTML = d + "/" + m + "<br> <b>" + y + "</b>";
    t = setTimeout (function() {renderTime()}, 500);
}

function checkTime(i) {
    if (i<10)
    {
        i = "0" + i;
    }
    return i;
}
</script>
Tareq Salah
  • 3,720
  • 4
  • 34
  • 48
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date – Salman Dec 25 '13 at 14:59
  • possible duplicate of [Javascript Date() constructor doesn't work](http://stackoverflow.com/questions/163563/javascript-date-constructor-doesnt-work) – Qantas 94 Heavy Dec 25 '13 at 15:10
  • 1
    possible duplicate of [getMonth in javascript gives last month](http://stackoverflow.com/questions/18624326/getmonth-in-javascript-gives-last-month) – KooiInc Dec 25 '13 at 15:15

3 Answers3

1

Months are zero-based in Javascript, so January is 0, February is 1, so on and so forth, until December is 11. Just add 1 to the today.getMonth(), and you'll be fine. Your new code would be

<script>
function renderDate() {
    var today = new Date();
    var d = today.getDate();
    var m = today.getMonth()+1;  //Month Increment
    var y = today.getFullYear();
    d = checkTime(d);
    m = checkTime(m);
    document.getElementById('dateid').innerHTML = d + "/" + m + "<br> <b>" + y + "</b>";
    t = setTimeout (function() {renderTime()}, 500);
}

function checkTime(i) {
    if (i<10)
    {
        i = "0" + i;
    }
    return i;
}
</script>
Mohit
  • 2,239
  • 19
  • 30
scrblnrd3
  • 7,228
  • 9
  • 33
  • 64
0

Month is Starting from zero

Replace

var m = today.getMonth()

with

var m = today.getMonth()+1

Tareq Salah
  • 3,720
  • 4
  • 34
  • 48
0

it's easily understand to you , i think :)
it's because the Date.prototype.getMonth() which return 0-11,representing the month 1 - 12

check the docs

user2228392
  • 404
  • 2
  • 10