Stephan - the curious
Stephan - the curious

Reputation: 423

How can I compare two dates and return years or days depending on difference?

I have this problem. I want to compare TODAY with a date (month, day, year) and return the age in days or years, depending if difference is smaller (return days) or greater (return years) than 1 year.

I get odd results.

That's my code:

function tellAge(month, day, year) {
	var d = new Date();
	var years = d.getFullYear()-year;
	var days = d.getDay()-day; 

	if ((d.getFullYear()-year)>1) {
		return "You are " + days + " days old"
	} else {
		return "You are " + years + " year old"
	}
 }

tellAge(3,11,2017)

This: tellAgeTest(3,11,2017) should return

You are 2 years old

but does not.

Upvotes: 0

Views: 199

Answers (2)

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23379

Your code doesn't work even if you fix the comparison operator.

In your current code you are subtracting d.getDay(), which is the day of the month (3 for Sept. 3rd) from the day entered (17 for Jan. 17th, in my example). This would work if both of the dates were in the same month, but if you want it to work across several months you have to count the number of days between the two dates and not just the difference between the days of the month.

function tellAge(month, day, year) {
  var today = new Date();
  var birthday = new Date(year, month-1, day);
  var days = (today - birthday) / (1000 * 60 * 60 * 24);
  
  if (days < 365) {
    return "You are " + Math.floor(days) + " days old"
  } else {
    return "You are " + Math.floor(days/365) + " years old"
  }
}

console.log(tellAge(1, 17, 2019));
console.log(tellAge(3, 11, 2017));

Upvotes: 2

CascadiaJS
CascadiaJS

Reputation: 2495

Your comparison is backwards. you should check for less than 1 not greater than one. Like this:

function tellAge(month, day, year) {
  var d = new Date();
  var years = d.getFullYear() - year;
  var days = d.getDay() - day;

  if ((d.getFullYear() - year) < 1) { // This comparison was backwards
    return "You are " + days + " days old"
  } else {
    return "You are " + years + " year old"
  }
}

Upvotes: 0

Related Questions