Home > Software design >  Checking if the entered date is the start of a quarter
Checking if the entered date is the start of a quarter

Time:05-06

Good afternoon! Can you please tell me how to implement a function that checks if the passed date is the beginning of the quarter? I tried to implement validation using the moment.js library and created a function

const isStartOfQuarter = (date: string) => {
  return moment(date).isSame(moment().quarter(moment(date).quarter()).startOf('quarter'), 'day')
}

When calling this function with the date "2022-04-01" it returns true and works correctly, but if you try to call it with the date "2023-04-01" it does not work correctly and returns false

I also need to make a function that checks if the passed date is the end of the quarter I created a function for this

const isEndOfQuarter = (date: string) => {
  return moment(date).isSame(moment().quarter(moment(date).quarter()).endOf('quarter'), 'day')
}

When calling this function with the date "2022-06-30" it returns true and works correctly, but if you try to call it with the date "2023-06-30" it does not work correctly and returns false

Can you please tell me how to implement this functionality correctly?

CodePudding user response:

I would just use the built-in Date type.

const isStartOfQuarter = (dateStr) => { 
  const d = new Date(dateStr); 
  return d.getUTCDate()==1 && d.getUTCMonth()%3==0
}

const isEndOfQuarter = (dateStr) => { 
  let d = new Date(dateStr); 
  d.setDate(d.getDate() 1); 
  return isStartOfQuarter(d);
}

Which work as advertised in Node:

> isStartOfQuarter("2023-04-01")
true
> isEndOfQuarter("2023-06-30")
true

CodePudding user response:

I would not suggest using momentjs. Even the authors recommend using alternatives for new developments.

In this case it is quite easy to do with native JavaScript, as there aren't that many quarters after all:

const isStartOfQuarter = (date) =>
    ["01-01", "04-01", "07-01", "10-01"].includes(date.slice(5, 10)); 

const isEndOfQuarter = (date) =>
    ["03-31", "06-30", "09-30", "12-31"].includes(date.slice(5, 10)); 

console.log(isStartOfQuarter("2023-04-01"));

  • Related