javascriptnode.jsexpressdatedayofmonth

How to get current month last and first date in nodejs


I am trying to get the first and last date of the month by the following code:-

let d = new Date();
let month = d.getMonth() + 1;
console.log(month);
let firstDate = new Date(d.getFullYear(), d.getMonth() + 1);
let lastDate = new Date(d.getFullYear(), d.getMonth() + 1);
console.log("First Date: ", firstDate);
console.log("Last Date", lastDate);

But I am getting output:-

First Date:  2023-06-30T18:30:00.000Z
Last Date 2023-06-30T18:30:00.000Z

or why I am not getting dates with zero hours ,minutes and seconds


Solution

  • why I am not getting dates with zero hours ,minutes and seconds

    Because you create firstDate and lastDate using the Date constructor and values for year and month. These are treated as local (i.e. the host system), but you are printing the timestamps as UTC. I guess your host system offset is +5:30, so instead of 1 July local you get 5:30 earlier UTC, so 30 June at 18:30.

    To do what you want using UTC, then use Date.UTC to generate the dates:

    function getStartAndEndOfMonthUTC(date = new Date()) {
      let y = date.getUTCFullYear();
      let m = date.getUTCMonth();
      let firstOfMonth = new Date(Date.UTC(y, m, 1));
      let lastOfMonth = new Date(Date.UTC(y, m+1, 0));
      return {firstOfMonth, lastOfMonth};
    }
    
    console.log(getStartAndEndOfMonthUTC());

    Your calculations are also wrong. The Date constructor wants the ECMAScript month (zero indexed), not the calendar month so don't add 1.

    Note that the UTC month start and end is different from the local start and end by the local timezone offset. So for +5:30 then at the end of June, it will not be midnight at the end of 30 June UTC until your local time is 5:30 on 1 July. So if you run the code at say 4:00 on 1 July and use the default date, it will return the start and end of June UTC.