0

I have this code:

const date = moment(person.indefiniteContractDate
  .toISOString()
  .substring(2),
  'YY-MM-DD');

if (date.isAfter('2020-08-15'))

I want to ask for the current year, but always for '08-15', how can I do that?

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
pmiranda
  • 7,602
  • 14
  • 72
  • 155
  • 1
    meh, new Date.getFullYear() – pmiranda Jul 20 '21 at 20:07
  • YY-MM-DD is a different string format than what you are searching for with the .isAfter Query. That is look for the format YYYY-MM-DD – BeerusDev Jul 20 '21 at 20:09
  • Doesn't the `moment` take a [`Date`](https://momentjs.com/docs/#/parsing/date/)? Just call `moment(person.indefiniteContractDate)`. If you need to set the hours/min/sec to zero, do so after passing in the `Date` object. Also, moment is EOL (end of life), you should use [Luxon](https://moment.github.io/luxon/#/) instead. – Mr. Polywhirl Jul 20 '21 at 20:35

2 Answers2

0

The moment function is capable of accepting a Date. Just call moment(person.indefiniteContractDate). If you need to set the hours/min/sec to zero, do so after passing in the Date object. There is a function called startOf that can handle setting the time to zero for the day.

Note: moment is EOL (end of life), you should use Luxon instead.

// IF
{
  const person = { indefiniteContractDate: new Date() }
  // https://stackoverflow.com/a/19699447/1762224
  const date = moment(person.indefiniteContractDate).startOf('day');

  if (date.isAfter('2020-08-15')) {
    console.log('AFTER!');
  }
}

// ELSE
{
  const person = { indefiniteContractDate: new Date(2020, 7, 13) }
  const date = moment(person.indefiniteContractDate).startOf('day');

  if (date.isAfter('2020-08-15')) {
    console.log('AFTER!');
  } else {
    console.log('BEFORE!'); // <-- Here
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
0

You can go by moment('08-15','MM-DD')

This will get you the 08-15 of current year

So I think your code could be

const date = moment(person.indefiniteContractDate
  .toISOString()
  .substring(2),
  'YY-MM-DD');

const compareDate = moment('08-15','MM-DD');

if (date.isAfter(compareDate))
Văn Vi
  • 51
  • 2