I'll post the full code below in case anyone is interested. This allows to calculate the age in years, months and days from the date of birth specified by the user to the current day (today).
The code works from a button on the toolbar, in JScript mode. I would really appreciate it if someone identifies a bug and lets me know, or if they have any suggestions.
Before I finish I want to thank everyone who helped me write this code, @Jon, @Leo , @lxp and very especially @bytespiller, not only for everything he helped me but also for everything he taught me!!!
function OnClick(clickData)
{
var dlg = clickData.func.Dlg;
//Birthdate
var date1String = dlg.getString("Enter birthdate (YYYY-MM-DD):");
if (!date1String) {
return;
}
//Convert birthdate (text) to true date (Date object)
var date1Array = date1String.split("-");
var yearString = date1Array[0];
var monthString = date1Array[1];
var dayString = date1Array[2];
var date1 = new Date(yearString, monthString - 1, dayString);
//Current date
var date2 = new Date();
if (!date2) {
return;
}
//Customize dates to show in the result (YYYY-MM-DD format, and days and months with 2 digits (0 to the left))
var yearF1 = date1.getFullYear();
var monthF1 = ("0" + (date1.getMonth()+1)).slice(-2);
var dayF1 = ("0" + date1.getDate()).slice(-2);
var date1Short = yearF1 + "-" + monthF1 + "-" + dayF1
var yearF2 = date2.getFullYear();
var monthF2 = ("0" + (date2.getMonth()+1)).slice(-2);
var dayF2 = ("0" + date2.getDate()).slice(-2);
var date2Short = yearF2 + "-" + monthF2 + "-" + dayF2
//Calculate time
var difference = date2 - date1; //In milliseconds
var total_days = Math.floor(difference / 24 * 60 * 60 * 1000); //In days
//Error message if birthdate > current date
if(difference < 0){
dlg.title = "Current age";
dlg.message = "Error: Birthdate must be less than current date.\n\nBirthdate: " + date1Short + "\nCurrent date: " + date2Short;
dlg.icon = "error";
dlg.buttons = "OK";
dlg.Show();
return;
}
//Calculate age
var age = new Date(0);
age.setMilliseconds(date2 - date1);
var years = age.getFullYear() - 1970;
var months = age.getMonth();
var days = age.getDate();
//Ignore 0 values and set singular or plural
var SEPARATOR = ", ";
function que(value, singular, plural) {
if (!value) {
return "";
}
var suffix = (Math.abs(value) > 1) ? plural : singular;
return value + " " + suffix + SEPARATOR;
}
var str_years = que(years, "year", "years");
var str_months = que(months, "month", "months");
var str_days = que(days, "day", "days");
var str_total = (str_years + str_months + str_days).slice(0, -SEPARATOR.length);
var result = str_total || "Born today";
//Show result
dlg.title = "Current age";
dlg.message = "Birthdate: " + date1Short + "\nCurrent age: " + date2Short + "\n\nEdad: " + result;
dlg.icon = "info";
dlg.buttons = "OK";
dlg.Show();
}
Calculate age....dcf (5.1 KB)