javascriptmomentjsmoment-timezone

Moment doesn't seem to be parsing my date calculations correctly


The code is suppposed to receive the age of a baby and make sure that it's not a date in the future and that the baby is not older than 2 years old.

import moment from "moment";

function datevalidation(baby_dob, current_date, diff) {
  if (
    !baby_dob.isBetween(current_date, current_date.clone().subtract(2, "years"))
  ) {
    if (diff > 0) {
      return "You entered a future date and your baby cannot be born in the future.";
    } else {
      return "Baby too old. Support is for only babies 22 years old and below";
    }
  }
  return "Baby age accepted";
}

var current_date = moment().startOf("day");
var baby_dob = new moment("20221204", "YYYYMMDD");
var diff = baby_dob.diff(current_date, "days");
datevalidation(baby_dob, current_date, diff);

I'm able to capture all future dates but anything else including the valid baby date of birth above (20221204) returns:

"Baby too old. Support is for only babies 22 years old and below".

Whereas I expect it to return:

Baby age accepted

It seems to me that something wrong os happening here:

!baby_dob.isBetween(current_date, current_date.clone().subtract(2, "years"))

It's supposed to check that the entered date is not older than 2 years from today and validate but it's not working.

Thanks.


Solution

  • Swap the order of the arguments to isBetween:

    !baby_dob.isBetween(current_date.clone().subtract(2, "years"), current_date)
    

    As noted in the documentation:

    Note that the order of the two arguments matter: the "smaller" date should be in the first argument.