Reputation: 53
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
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
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
Reputation: 3718
Month is Starting from zero
Replace
var m = today.getMonth()
with
var m = today.getMonth()+1
Upvotes: 0