开发者

Javascript help fixing a working time ago date function to simply show seconds ago

edited, this is it

function handleDate( timestamp ) {
        var n=new Date(), t, ago = " ";
        if( timestamp ) {
         t =   Math.round( (n.getTime()/1000 - timestamp) );

          ago += handleSinceDateEndings( t, timestamp );
        } else {
            ago += "";
        }
        return ago;
    }    

    function handleSinceDateEndings( t, original_timestamp ) {
    var ago = " ", date;
// If our timestamp is unde开发者_开发技巧r 60 we are dealing with seconds.
if( t < 60 ) {
    ago += t + " seconds ago";
    is_seconds = true;

//Otherwise, we are dealing with minutes -- let's adjust t to minutes to avoid
//re-writing the rest of the loop.
} else {
    t /= 60;
    is_seconds = false
}
if( is_seconds === false ) {
if( t<60 ) {

            ago += Math.round(t) + " mins ago";
        } else if( t>= 60 && t<= 120 ) {
            ago += Math.floor( t / 60 ) + " hour ago"
        } else if( t<1440 ) {
            //console.log(t)
            ago += Math.floor( t / 60 )  + " hours ago";
        } else if( t< 2880) {
            ago +=  "1 day ago";
        } else if( t > 2880  && t < 4320 ) {
            ago +=  "2 days ago";
        } else {
            date = new Date( parseInt( original_timestamp )*1000 ) 
            ago += months[ date.getMonth() ] + " " + date.getDate();
        }
}

        return ago;
    }

    var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];


Inside of handelDate() change:

 t =   Math.round( (n.getTime()/1000 - timestamp)/60 ); 

to

t =   Math.round( (n.getTime()/1000 - timestamp) );
// Give us seconds, not minutes.

In your handleSinceDateEndings() change:

var ago = " ", date;
if( t <= 1 ) {
        ago += t + " seconds ago";
    } else if( t<60) {

to

var ago = " ", is_seconds = false, date;
// If our timestamp is under 60 we are dealing with seconds.
if( t < 60 ) {
    ago += t + " seconds ago";
    is_seconds = true;

//Otherwise, we are dealing with minutes -- let's adjust t to minutes to avoid
//re-writing the rest of the loop.
} else {
    t /= 60;
}
if( t<60 && is_seconds === false) {


I suggest using a library: http://timeago.yarp.com/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜