Skip to Content

timeAgo()

Convert a timestamp to relative time.

JavaScript April 17, 2021

Usage

JavaScript
nebula.timeAgo(timestamp)

Parameters

timestamp
(Required) (Date Object or String) In specific timestamp format (See below)
Default: None

Parameter Notes

Pass timestamp in the format Fri Mar 27 21:40:02 +0000 2016

Request or provide clarification »

Examples

JavaScript
let loadedTime = new Date();
jQuery('#example').on('mouseover', function(){
    let timeSinceLoaded = nebula.timeAgo(loadedTime);
    console.log(timeSinceLoaded); //-> 2 minutes ago
});

Additional Notes

This is useful for Twitter posts.

Source File

Located in /assets/js/modules/utilities.js on line 624.

No Hooks

This function does not have any filters or actions available. Request one?
JavaScript
nebula.timeAgo = function(timestamp, raw){ //http://af-design.com/blog/2009/02/10/twitter-like-timestamps/
    if ( !timestamp instanceof Date ){
        nebula.help('Pass date as string in the format: Fri Mar 27 21:40:02 +0000 2016 (Your format: ' + timestamp + ')', '/functions/timeAgo/');
    }

    let postDate = new Date(timestamp);
    let currentTime = new Date();
    let diff = Math.floor((currentTime-postDate)/1000);

    if ( raw ){
        return diff;
    }

    if ( diff <= 1 ){ return 'just now'; }
    if ( diff < 20 ){ return diff + ' seconds ago'; }
    if ( diff < 60 ){ return 'less than a minute ago'; }
    if ( diff <= 90 ){ return '1 minute ago'; }
    if ( diff <= 3540 ){ return Math.round(diff/60) + ' minutes ago'; }
    if ( diff <= 5400 ){ return '1 hour ago'; }
    if ( diff <= 86_400 ){ return Math.round(diff/3600) + ' hours ago'; }
    if ( diff <= 129_600 ){ return '1 day ago'; }
    if ( diff < 604_800 ){ return Math.round(diff/86_400) + ' days ago'; }
    if ( diff <= 777_600 ){ return '1 week ago'; }

    return 'on ' + timestamp;
};

Override

To override or disable this JavaScript function, simply redeclare it with the exact same function name.

JavaScript
nebula.timeAgo = function(timestamp){
    //Write your own code here, leave it blank, or return false.
}