skip to Main Content

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

2

Answers


  1. You can try this:

    let firstDate = new Date(d.getFullYear(), d.getMonth())
    let lastDate = new Date(new Date(d.getFullYear(), d.getMonth() + 1) - 1)
    

    Explanation:

    1. firstDate: You pretty much had the firstDate correct except an extra "+1" which fetched you the date from next month. So just removing the "+1" will solve it.
    2. lastDate: I’m adding 1 to get the firstDate of next month and then subtracting 1 (which converts to epoch time of lastDate of current month, and then converting back from epoch to date format.
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search