Skip to content

Instantly share code, notes, and snippets.

@8bitspixel
Last active February 24, 2023 02:51
Show Gist options
  • Save 8bitspixel/01775011cd553f68a6da464f32a7cb7e to your computer and use it in GitHub Desktop.
Save 8bitspixel/01775011cd553f68a6da464f32a7cb7e to your computer and use it in GitHub Desktop.
Calculate the days until your next birthday with MomentJS

Next birthday with momentJs:

DaysUntil accepts a momentJS object with a birthday date which returns amount of days left

##Using a momentJS object with the day of your next birthday

function daysUntil(date) {
  var birthday = moment(date);
  var today = moment().format("YYYY-MM-DD");
  
  if (birthday.isSame(today)) {
    return 'Cake!!';
  } else {
    return 'Days until next birthday' + ' ' + birthday.diff(today, 'days');
  }
}

var result = daysUntil("2017-03-25");
console.log(result);

##Using a momentJS object with your born date:

function daysUntil(date) {
  var birthday = moment(date);
  
  // uncomment this line to simulate it is your birthday and comment the next one to test it.
  // var today = moment("2017-03-25");
  var today = moment().format("YYYY-MM-DD");
  
  // calculate age of the person
  var age = moment(today).diff(birthday, 'years');
  moment(age).format("YYYY-MM-DD");
  console.log('person age', age);
  
  var nextBirthday = moment(birthday).add(age, 'years');
  moment(nextBirthday).format("YYYY-MM-DD");
  
  /* added one more year in case the birthday has already passed
  to calculate date till next one. */
  if (nextBirthday.isSame(today)) {
    return 'Cake!!';
  } else {
    nextBirthday = moment(birthday).add(age + 1, 'years');
    return 'Days until next birthday' + ' ' + nextBirthday.diff(today, 'days');
  }
}

var result = daysUntil("1986-03-25");
console.log(result);
@mcfaith9
Copy link

How aboult calculate upcoming birthday via 60 days?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment