0

I want to calculate age of anything.i already wrote the program. I took a date object and assigned value into it $birth_date=new Date('Dec,15,1992'); then i subtract the value with the current data.According to the subtraction it should returns 23 years 0 months 14 days.but it returns 23 years 4 months 14 days.years and days are OK but the month misleads.

would you pls tell me why showing this weird results?

following code is HTML and next to Javascript

$(document).ready(function(){
var birth_date = new Date('Dec, 15, 1992').getTime();

var years,months,days, hours, minutes, seconds;
var ageCount = document.getElementById('counter');
setInterval(function(){

 var current_date = new Date().getTime();
 var total_sec =(current_date-birth_date) / 1000;
 years=parseInt(total_sec/(86400*30*12));
 var second_left=total_sec%(86400*30*12);
 months=parseInt(second_left/(86400*30));
 second_left=second_left%(86400*30);
 days=parseInt(second_left/86400);
 second_left=second_left%(86400);
 hours=parseInt(second_left/3600);
 second_left=second_left%3600;
 minutes=parseInt(second_left/60);
 seconds=parseInt(second_left%60);


  ageCount.innerHTML=years+' Years '+months+' Months '+days+' Days '+hours+
 ' Hours '+minutes+' Minutes '+seconds+' Seconds';

},500);

});
<div id="counter">
 
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
hmamun
  • 154
  • 1
  • 15
  • these date questions keep coming a lot.. does anyone have a universal link to cover these problems? – CoderPi Dec 28 '15 at 19:57
  • 5
    months are always 30 days? – Mi-Creativity Dec 28 '15 at 19:59
  • 2
    I have one additional problem for you. Leap years... – wegelagerer Dec 28 '15 at 20:02
  • 2
    That "duplicate" only pertains to the number of years lapsed, right? – Charlie Dec 28 '15 at 20:11
  • I understood the problem.among the 12 months 7 months are 31 days and 4 months are 30 days 1 month is 28 days.so each year it increments by 5 days,since I took 1 month =30days.so in 23 years it will be 115 days and it got minimum 5 leap years that means another 5 days.so total days are now 115+5=120/30=4months. could u pls tell me how could i solve the problem? – hmamun Dec 28 '15 at 20:13
  • @hmamun If you did the math separate from the initial calculation (which I wouldn't recommend, it's redundant), you could just subtract the correction. – Charlie Dec 28 '15 at 20:14
  • 1
    Also, since I don't believe this is a duplicate, I don't see any reason to downvote this question. While the issues might seem trivial, @hmamun posted a legitimate question and even included a legitimate attempt at solving it. – Charlie Dec 28 '15 at 20:15

3 Answers3

0

I think it would make more sense to just use the basic notations as listed here for getting metrics such as date , hour , minutes, seconds from the date difference

$(document).ready(function(){
var birth_date = new Date('Feb, 15, 1992');

var years,months,days, hours, minutes, seconds;
var ageCount = document.getElementById('counter');
setInterval(function(){

var current_date = new Date();
var YearDiff =  (current_date.getYear() - birth_date.getYear());
var monthDiff = (current_date.getMonth() - birth_date.getMonth());
var daysDiff = (current_date.getDate() - birth_date.getDate());
var hoursDiff = (current_date.getHours() - birth_date.getHours());
var minDiff = (current_date.getMinutes() - birth_date.getMinutes());
var secDiff = (current_date.getSeconds() - birth_date.getSeconds());


     ageCount.innerHTML=YearDiff+' Years '+monthDiff+' Months '+daysDiff+' Days '+hoursDiff+
    ' Hours '+minDiff+' Minutes '+secDiff+' Seconds';

},500);

});

https://jsfiddle.net/DinoMyte/138bhovx/2/

DinoMyte
  • 8,737
  • 1
  • 19
  • 26
-1

You Can simply make this calculation with the following implementation.

https://jsfiddle.net/wqm704xm/1/

var birthday = new Date('Dec,15,1992');
var today;
var $dateEl = document.getElementById('date');

setInterval(writeValue, 100);

function writeValue() {
   today = new Date();
   var calculatedDate = calculate(normalizeDate(birthday), normalizeDate(today));

   $dateEl.innerHTML = 
    'years: ' + calculatedDate.year + '<br>' +
    'months: ' + calculatedDate.month + '<br>' +
    'days: ' + calculatedDate.day + '<br>' +
    'hours: ' + calculatedDate.hours + '<br>' +
    'minutes: ' + calculatedDate.minutes + '<br>' +
    'seconds: ' + calculatedDate.seconds + '<br>' 
  ;
}
  

function calculate(firstDate, currentDate) {
     return {
         year: currentDate.year - firstDate.year,
         month: currentDate.month - firstDate.month,
         day: currentDate.day - firstDate.day,
         hours: currentDate.hours - firstDate.hours,
         minutes: currentDate.minutes - firstDate.minutes,
         seconds: currentDate.seconds - firstDate.seconds
     }
}

function normalizeDate(date) {
  return {
    year: date.getFullYear(),
    month: date.getMonth() + 1,
    day: date.getDate(),
    hours: date.getHours(),
    minutes: date.getMinutes(),
    seconds: date.getSeconds()
  };
}
<div id="date"></div>
Saif Adnan
  • 307
  • 3
  • 12
-3

Months is incorrect because you are assuming that every month is only 30 days long, when months can be 28, 29, 30 or 31 days in length (and in some circumstances, other lengths).

To quickly see where you are going wrong, and ignoring leap years, 30/days a month would mean 30*12 only 360 days per year. That means every year you miss 5 days. So given 23 years, that's roughly 23*5 days difference, or ~4 months.

There were 5 leap years in between your date and now, adding 5 more days to the difference. This completely accounts for your 4 months (120 days).

You need to adjust your algorithm to account for these differences.

Additional info:

If you are using this in production code and require accurate dates - please keep in mind a date is not sufficient information to calculate precise differences in terms of number of days. You'll also need information such as time zone and location and handle all sorts of lovely time discontinuations.

For example: In 2011 Samoa jumped to the other side of the international date line. So 29-Dec-2011 to 1-Jan-2012 is 1 day longer in Australia than it was in Samoa.

(╯°□°)╯︵ ┻━┻

Dan McGrath
  • 41,220
  • 11
  • 99
  • 130
  • 2
    @cybermonkey: Your linked duplicate does not answer the OP's question (years vs years, months and days) and I answered this before it was linked as duplicate – Dan McGrath Dec 28 '15 at 20:16
  • You answered this ~1 minute *after* it was marked as a duplicate (probably didn't show 'til you submitted though). – AStopher Dec 28 '15 at 20:21
  • 1
    @cybermonkey It's not even a duplicate though – Charlie Dec 28 '15 at 20:22
  • 1
    I think we can keep 1 minute between friends. The point on your linked duplicate not answering the question still stands. We don't close questions on SO by marking them as dups that are not.. dups. – Dan McGrath Dec 28 '15 at 20:23
  • 2
    PS: I'll happily take the down votes as long as this helps @hmamun - which is after all why we are here. – Dan McGrath Dec 28 '15 at 20:25