Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

268
Views
Calculating time elapsed javascript wrong output

I am currently using a script to calculate the time passed in years, months, days etc in Javascript.

 $(document).ready(function(){
var birth_date = new Date('March, 25, 2022');

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);

});`

This seems to output the right months, days and hours when the set date day is lower than the current date (so April 21 when it is now April 22).

0 Years 1 Months 2 Days 8 Hours 14 Minutes 2 Seconds`

When the date day number is higher, it changes it to a certain number of months minus a number of days. Like this (1 month - 4 days, when it should just be 0 months and 27 days).

0 Years 1 Months -4 Days 8 Hours 14 Minutes 38 Seconds

An example of the script is viewable here: https://jsfiddle.net/j2k7n4zp/

Does anyone have a clue what goes wrong or what I need to fix to make it calculate the right amount of days without using minus?

Thanks in advance!

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

What's going wrong with your code is that assume every part of a later date is higher than every part of an earlier one ... e.g. ... 23 April 2022 to 1 May 2022 - the Date is lower, but the Month is higher - whereas your code naively the Date portion of 1 May is Higher than 23 April just because May is later than April - but that's not how dates work

Here's something I literally whipped up now, see if it helps

const dateDiff = (from, to) => {
    // so we don't mutate passed in dates
    let start = new Date(from);
    let end = new Date(to);
    if (+start > +end) {
        [start, end] = [end, start];
    }
    const loop = (prop) => {
        const set = `set${prop}`;
        const get = `get${prop}`;
        let ret = 0;
        while (1) {
            start[set](start[get]() + 1);
            if (start < end) {
                ret++;
            } else {
                start[set](start[get]() -1);
                break;
            }
        }
        return ret;
    }
    const years = loop('FullYear'); 
    const months = loop('Month'); 
    const days = loop('Date'); 
    const hours = loop('Hours'); 
    const minutes = loop('Minutes'); 
    const seconds = loop('Seconds'); 
    const milliseconds = loop('Milliseconds'); 
    return {years, months, days, hours, minutes, seconds, milliseconds}
}
const ageCount = document.getElementById('counter');
setInterval(() => {
    const r = dateDiff(new Date(), new Date('2022-03-25'));
    ageCount.innerHTML = `${r.years} Years, ${r.months} Months, ${r.days} Days, ${r.hours} Hours, ${r.minutes} Minutes, ${r.seconds} Seconds`;
}, 500);
<div id="counter">
    
</div>

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!