Reylin Mathew

Reylin Mathew

  • NA
  • 347
  • 76.1k

how to age and month from date

Jul 17 2021 2:19 PM

Age calculation

DOB = 2010-07-01(July)

DATE = 2026-08-01 (August)

correct age is  = 15 yrs 11 mnths

but this code returns = 16 yr 1 mnt..

my code attached also,

  

var age = retoday.getFullYear() - dob.getFullYear();
        var mnth = 0;
        if (today.getMonth() == 0) {
            mnth = (today.getMonth() + 1) - dob.getMonth();
        }
        else
            tmnth = today.getMonth() - dob.getMonth();
        if (tmnth < 0 || (retmnth == 0 && (today.getDate() < dob.getDate()))) {
            tage--;
        }

 

plz hlp me...thnkx in adv

 

 


Answers (2)

2
Sachin Singh

Sachin Singh

  • 7
  • 55.8k
  • 82.8k
Jul 17 2021 8:58 PM
Before doubting the Logic, have you did the common real-life calculation its simply 16 years 1 month. 
Your code is correct.
for calculating DOB, we first subtract the daypart then month part, and then the year part,  
 
example:- 
   18-07-2021     (borrowed 1 month(30+18) then borrowed 1year (12+6=18) year left=2020)
-  21-11-1995
_____________
   27- 07-25
1
Vikas Jha

Vikas Jha

  • 628
  • 1.7k
  • 292.6k
Jul 17 2021 4:37 PM
I think your code is returning correct value . I tried same and got the same value .
  1. var dob = "07/01/2010"debugger;   
  2. var dobTill = "08/01/2026";  
  3.  var nextDate = new Date(dobTill);  
  4.     var birthDate = new Date(dob);  
  5.     var age = nextDate.getFullYear() - birthDate.getFullYear();  
  6.     var m = nextDate.getMonth() - birthDate.getMonth();  
  7.     if (m < 0 || (m === 0 && nextDate.getDate() < birthDate.getDate())) {  
  8.         age--;  
  9.     }  

Then I tried as above image and it gave me same result. Please let me know if solved your issue.