wobsoriano
wobsoriano

Reputation: 13434

How to check if expiration date is under a month?

I have a code that checks the number of days left given the expiration date:

const expiration = "2019-10-25T01:41:02.523Z";
const daysLeft = Math.floor((Date.parse(expiration) - Date.now()) / (24 * 60 * 60 * 1000));

console.log(daysLeft);

Now I want to check if the current date is under a month from the given expiration date.

I tried using moment but I'm not sure if I am doing it right

const now = moment().add(1, 'M');
const expires = moment(expiration);

if (now.isBefore(expires)) {
  // expired
}

How can I achieve this? Thanks in advance.

Upvotes: 1

Views: 1498

Answers (1)

Blue
Blue

Reputation: 22911

I think you want to just reverse your logic, and use isAfter(). If we log 2019-10-25T01:41:02.523Z it now shows "under a month", and if we increment that to "2019-11-25" it no longer shows a console.log message:

const expiration = "2019-10-25T01:41:02.523Z";

const now = moment().add(1, 'M');
const expires = moment(expiration);

if (now.isAfter(expires)) {
  console.log(expiration, 'under a month');
} else {
  console.log(expiration, 'not under a month');
}


const expiration2 = "2019-11-25T01:41:02.523Z";

const expires2 = moment(expiration2);

if (now.isAfter(expires2)) {
  console.log(expiration2, 'under a month');
} else {
  console.log(expiration2, 'not under a month');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Upvotes: 3

Related Questions