Search code examples
javascriptdatedatetimeutc

JavaScript: unexpected result getting number of days remaining in the month


I'm building a simple script to show the number of days to the end of the month to demonstrate an understanding of how dates work in Javascript. Which is just as well, because I clearly don't have one.

I want to get the current date, and compare it to the last day of the month, as date(this year, this month +1, day 0) - 1 day to see how many days are left. I could build an array telling it how many days are in each month, but I should be able to use the inbuilt understanding of dates to resolve this.

For expected output, last day of this month (Aug 31) - today (Aug 30) = 1. But I'm getting 0.

This is what I have so far:

<p id="demo"></p>

<script>
var d = new Date();
var nxt = new Date(d.getFullYear(), d.getMonth() + 1, 0);
nxt.setDate(nxt.getDate() - 1);
document.getElementById("demo").innerHTML = nxt.getDay() - d.getDay();
</script>

At the moment it's 11 in AEST (GMT + 1000), which is where I'm at in case that's of any help. Point is to make something that would work anywhere, any time.


My first suspect is timezones - I thought that this might even out if I used all UTC or no UTC explicits. It doesn't seem to be doing so though. I've tried asking for UTC values in a range of different places, but oddly only seem to be able to increase the inaccuracy so it returns -1.


Solution

  • I believe I just stumbled on the answer - when specifying a date months are counted from 0 to 11, but days are still counted from 1 to 31. Therefore, specifying

    Date(d.getFullYear(), d.getMonth() + 1, 0);
    

    is basically shorthand for the last day of the current month. The next line is then redundant:

    nxt.setDate(nxt.getDate() - 1);
    

    This will give an incorrect result, as it basically decrements a second time. The problem is not with UTC/nonUTC, but rather incorrect day specification. Not sure if this shorthand could cause other problems further down the line though.