SaaS Developer   
   About    Testimonials    Contact   

How much time has passed?

Two weeks have passed since I started my JavaScript Marathon along with writing this blog! Time to celebrate.

Just yesterday, I worked with Dates in JavaScript. So to celebrate this day, I created a universal function, which tells you the time that has passed from any moment in the past till the present moment. Let’s go!

Here we go. Let’s create a function, which would take any Date as an argument and return us the information on how long ago it happened:

function analyzeDate(date) {

    var now = new Date();
    var diff = Math.round(now - date);
    
    if ( diff < 1000 ) {
        return('Now');
    
    } else if ( diff >= 1000 && diff < 60*1000) {
        return( diff/1000 +' seconds ago');
    
    } else if ( diff >= 60000 && diff < 60*60*1000) {
        return ( diff/60000 +' minutes ago'); // 55 minutes ago
    
    } else {
        return reformatDate(date);
    }
}

As an additional feature, I’d like to change the Date output into European format so it is presented as dd.mm.yy hh:mm:

function reformatDate(date) {

    var fullDate = [];
    var fullTime = [];

    var day = date.getDate()+'';
    var month = date.getMonth()+1+'';
    var year = date.getFullYear()+'';
    var hours = date.getHours()+'';
    var minutes = date.getMinutes()+'';

    if (day.length <2) { day = '0'+day; }
    if (month.length <2) { month = '0'+month; }
    if (year.length < 2) { year = '0'+year;}
    if (hours.length <2) { hours = '0'+hours; }
    if (minutes.length < 2) { minutes = '0'+minutes;}

    fullDate.push(day);
    fullDate.push(month);
    fullDate.push( year.slice(-2) );
    fullTime.push(hours);
    fullTime.push(minutes);

    return fullDate.join('.')+' '+fullTime.join(':');
}

Now, to check the result, let’s alert the following cases:

alert( analyzeDate( new Date(new Date - 1) ) );
alert( analyzeDate( new Date(new Date - 30*1000) ) );
alert( analyzeDate( new Date(new Date- 5*60*1000) ) );
alert( analyzeDate( new Date(new Date - 86400*1000) ) );

You may try it live at JSFiddle or by clicking “Results” below:


comments powered by Disqus