user2825417
user2825417

Reputation: 53

JavaScript code messing with date

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>

Upvotes: 0

Views: 60

Answers (3)

scrblnrd3
scrblnrd3

Reputation: 7426

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>

Upvotes: 1

user2228392
user2228392

Reputation: 404

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

Upvotes: 0

Tareq Salah
Tareq Salah

Reputation: 3718

Month is Starting from zero

Replace

var m = today.getMonth()

with

var m = today.getMonth()+1

Upvotes: 0

Related Questions