Calculating age with JavaScript

219 views
Skip to first unread message

eDog

unread,
Nov 23, 2017, 11:46:40 AM11/23/17
to mementodatabase
This script will calculate the age with an accuracy of one day:

var birthDate = field("BirthDay")
var result
if (birthDate == undefined)
{result = 'Age not known'}
else
{
var dat = new Date();
var curday = dat.getDate();
var curmon = dat.getMonth()+1;
var curyear = dat.getFullYear();

function checkleapyear(datea)
{
if(datea.getYear()%4 == 0)
{
if(datea.getYear()% 10 != 0)
{
return true;
}
else
{
if(datea.getYear()% 400 == 0)
return true;
else
return false;
}
}
return false; }

function DaysInMonth(Y, M)
{
with (new Date(Y, M, 1, 12))
{
setDate(0);
return getDate();
} }

function datediff(date1, date2)
{
var y1 = date1.getFullYear(),
m1 = date1.getMonth(),
d1 = date1.getDate(),
y2 = date2.getFullYear(),
m2 = date2.getMonth(),
d2 = date2.getDate();

if (d1 < d2) {
m1--;
d1 += DaysInMonth(y2, m2);
}
if (m1 < m2) {
y1--;
m1 += 12;
}
return [y1 - y2, m1 - m2, d1 - d2]; }

function calage()
{
var calyear = birthDate.getFullYear();
var calmon = birthDate.getMonth()+1
var calday = birthDate.getDate()

var curd = new Date(curyear,curmon-1,curday);
var cald = new Date(calyear,calmon-1,calday);
var diff =
Date.UTC(curyear,curmon,curday,0,0,0) - Date.UTC(calyear,calmon,calday,0,0,0);
var dife = datediff(curd,cald);

var age
if(dat < birthDate)
{age = '!!!Invalid date'}
else
{age = dife[0]+" years, "+dife[1]+" months, and "+dife[2]+" days";}
return age;
}
result = calage(birthDate)}
result

mandraek

unread,
Feb 9, 2018, 9:56:31 AM2/9/18
to mementodatabase
thanks, works perfectly! :)

luci...@gmail.com

unread,
Oct 2, 2020, 2:54:54 PM10/2/20
to mementodatabase
Reabrindo esse topico:

Boa noite Edog
Estou com um problema com esse seu script deu certo encontrar entre duas datas anos meses e dias. Preciso entretanto de valores em semanas e dias acumulados como eu farei para modificar esse script? Por exemplo entre essas datas abaixo:
Data da IG (idade gestacional)=02/10/2020
Data da gestaçao= 10/05/2020.Encontrei por esse script: 0 anos, 4 meses e 22 dias.
Fui orientado por Gilles para te procurar. Queria converter esse calculo para semanas e dias acumulados.
Obrigado
Lucidio

Good night Edog I have a problem with that your script worked well between two dates years months and days. However, I need values ​​in accumulated weeks and days as I will do to modify this script? For example, enter these dates below: GI date (gestational age) = 10/10/2020 Management date = 10/05 / 2020.I found by this script: 0 years, 4 months and 22 days. I was guided by Gilles to look for you. I wanted to convert this calculation to accumulated weeks and days. Thank you Lucidio  

Reply all
Reply to author
Forward
0 new messages