Skip to Content

timeAgo()

Convert a timestamp to relative time.

JavaScript July 2, 2019

Usage

JavaScript
nebula.timeAgo(timestamp)

Parameters

timestamp
(Required) (String) A string in specific timestamp format (See below)
Default: None

Parameter Notes

Pass timestamp as a string (not a Date object) in the format Fri Mar 27 21:40:02 +0000 2016

Request or provide clarification »

Additional Notes

This is useful for Twitter posts.

Source File

Located in /assets/js/nebula.js on line 4229.

JavaScript
nebula.timeAgo = function(timestamp, raw){ //http://af-design.com/blog/2009/02/10/twitter-like-timestamps/
    if ( typeof timestamp === 'object' ){
        console.warn('Pass date as string in the format: Fri Mar 27 21:40:02 +0000 2016');
    }

    var postDate = new Date(timestamp);
    var currentTime = new Date();

    //Browser sanitation
    if ( jQuery('.ie, .internet_explorer, .microsoft_edge').length ){
        postDate = Date.parse(timestamp.replace(/( \+)/, ' UTC$1'));
    }

    var 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 "one minute ago"; }
    if ( diff <= 3540 ){ return Math.round(diff/60) + " minutes ago"; }
    if ( diff <= 5400 ){ return "1 hour ago"; }
    if ( diff <= 86400 ){ return Math.round(diff/3600) + " hours ago"; }
    if ( diff <= 129600 ){ return "1 day ago"; }
    if ( diff < 604800 ){ return Math.round(diff/86400) + " days ago"; }
    if ( diff <= 777600 ){ 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.
}