Friday, August 26, 2011

Servoy TIP: Calculating Age

Calculating the age of something (or someone) is a task that I come across a lot. Here's a simple function that will help get you the basics:

function getAge(myDate){
  // myDate= new Date("7/12/1968")
  var now = new Date();
  var yr = now.getFullYear() - myDate.getFullYear();
  var mo = now.getMonth() - myDate.getMonth();
  if(mo < 0) {
  mo = myDate.getMonth() - now.getMonth();
  }
  var days = now.getDate() - myDate.getDate();
  if(days < 0) {
  days = myDate.getDate - now.getDate();
  }
  var agestr = yr + " years, " + mo + " months, " + days + " days";
  plugins.dialogs.showInfoDialog("Date DIff", agestr,"OK");

}
You can (should) enhance the function by checking the years, months and days for plurality and modifying the strings accordingly:

function getAge(myDate){
  // myDate= new Date("7/12/1968")
  var now = new Date();
  var yrTxt = "year";
  var moTxt = "month";
  var dayTxt = "day";

  var yr = now.getFullYear() - myDate.getFullYear();
  if(yr != 1) {
  yrTxt += "s";
  }
  var mo = now.getMonth() - myDate.getMonth();
  if(mo < 0) {
  mo = myDate.getMonth() - now.getMonth();
  }
  if(mo != 1) {
  moTxt += "s"
  }
  var days = now.getDate() - myDate.getDate();
  if(days < 0) {
  days = myDate.getDate - now.getDate();
  }
  if(days != 1) {
  dayTxt += "s";
  }
  var agestr = yr + " " + yrTxt + ", " + mo + " " + moTxt + ", " + days + " " + dayTxt;
  plugins.dialogs.showInfoDialog("Date DIFF", agestr,"OK");

}

Happy age calculating...

No comments:

Post a Comment