BreezyChick89
BreezyChick89

Reputation: 1479

How do I get the how many days until my next birthday?

I tried this but it fails

var diffDays1=(function(){ 
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var secondDate = new Date(new Date().getFullYear()+1,4,5);
var firstDate = new Date();
 return Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
})();

Wolfram alpha says it's 330 days, diffDays1 shows it's 359. This is probably due to daylight savings or something. Is there a way to accurately calculate days since without doing it server side.

Upvotes: 12

Views: 16618

Answers (5)

LStarky
LStarky

Reputation: 2777

Here's a cleaner solution using moment, which handles all cases correctly (including today, upcoming birthday this year or not until next year, time zone, leap year, etc.):

const birthdate = '2018-12-15';
const today = moment().format('YYYY-MM-DD');
const years = moment().diff(birthdate, 'years');
const adjustToday = birthdate.substring(5) === today.substring(5) ? 0 : 1;
const nextBirthday = moment(birthdate).add(years + adjustToday, 'years');
const daysUntilBirthday = nextBirthday.diff(today, 'days');

Simple, fast, accurate!

Here's the same code, explained:

// This is the birthdate we're checking, in ISO 8601 format
const birthdate = '2018-12-15';

// Get today's date in ISO 8601 format
const today = moment().format('YYYY-MM-DD');

// Calculate current age of person in years (moment truncates by default)
const years = moment().diff(birthdate, 'years');

// Special case if birthday is today; we do NOT need an extra year added
const adjustToday = birthdate.substring(5) === today.substring(5) ? 0 : 1;

// Add age plus one year (unless birthday is today) to get next birthday
const nextBirthday = moment(birthdate).add(years + adjustToday, 'years');

// Final calculation in days
const daysUntilBirthday = nextBirthday.diff(today, 'days');

If the birthday is today, the result will be 0; if it is tomorrow, the result will be 1, and so on.

Upvotes: 3

Lucas Janon
Lucas Janon

Reputation: 1612

The selected solution doesn't work if the birthday is this year, because it sums 1 to getFullYear.

This is my solution, it also prevents two edge cases: birthday today and 1 day remaining.

const birthdayDay = 19;
const birthdayMonth = 11; // december === 11
const myBirthdayThisYear = new Date(new Date().getFullYear(), 11, 19).setHours(23, 59, 59);

export const daysUntilBirthday = () => {
  const addToYear = myBirthdayThisYear > Date.now() ? 0 : 1;
  const oneDay = 24 * 60 * 60 * 1000;
  const secondDate = new Date(new Date().getFullYear() + addToYear, birthdayMonth, birthdayDay);
  const firstDate = new Date();
  const days = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay)));
  const daysOrDay = days === 1 ? 'day' : 'days';
  return days !== 365 ? `${days} ${daysOrDay} until my birthday 😉😉` : '🎂 TODAY IS MY BIRTHDAY 🎂';
};

Upvotes: 0

user694844
user694844

Reputation: 1187

The problem is that you're basing the month on April being 4, when April is 3 in Javascript. See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date#Parameters

var diffDays1=(function(){ 
    var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
    var secondDate = new Date(new Date().getFullYear()+1,3,5);
    var firstDate = new Date();
    return Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
})();

Upvotes: 21

andrunix
andrunix

Reputation: 1754

The moment.js library (http://momentjs.com) handles this and a lot of other JavaScript date issues very easily and nicely. The diff function (http://momentjs.com/docs/#/displaying/difference/) will do exactly what you want.

The fromNow function is also super nice if want to display the number of days from now you could do something like:

moment([2014, 4, 5]).fromNow();

would produce something like "330 days" if it's 330 days away.

http://momentjs.com/docs/#/displaying/fromnow/

Upvotes: 2

aorlando
aorlando

Reputation: 668

Why reinvent the wheel?? Use datejs

and after:

var startd = Date.parseExact(ind, "yyyy-MM-dd");
var endd = Date.parseExact(end, "yyyy-MM-dd");
var diff = new Date(endd - startd);
var days = diff/1000/60/60/24;

That's all folks!

Upvotes: 5

Related Questions