Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to make time slice using Javascript

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 815
    Comment on it

    Hello Reader's If you are genrating the time in Unix time stamp and want to show it like 5 min ago or 3 hours ago then you can use the code below:-

    Here we are using NOW of the unix timestamp

    function timeSince(ts){
        now = new Date();
        ts = new Date(ts*1000);
        var delta = now.getTime() - ts.getTime();
    
        delta = delta/1000; //us to s
    
        var ps, pm, ph, pd, min, hou, sec, days;
    
        if(delta<=59){
            ps = (delta>1) ? "s": "";
            return delta+" second"+ps
        }
    
        if(delta>=60 && delta<=3599){
            min = Math.floor(delta/60);
            sec = delta-(min*60);
            pm = (min>1) ? "s": "";
            ps = (sec>1) ? "s": "";
            return min+" minute"+pm+" "+sec+" second"+ps;
        }
    
        if(delta>=3600 && delta<=86399){
            hou = Math.floor(delta/3600);
            min = Math.floor((delta-(hou*3600))/60);
            ph = (hou>1) ? "s": "";
            pm = (min>1) ? "s": "";
            return hou+" hour"+ph+" "+min+" minute"+pm;
        } 
    
        if(delta>=86400){
            days = Math.floor(delta/86400);
            hou =  Math.floor((delta-(days*86400))/60/60);
            pd = (days>1) ? "s": "";
            ph = (hou>1) ? "s": "";
            return days+" day"+pd+" "+hou+" hour"+ph;
        }
    
    }
    

    Output:- The output format of the function will be like . 4 sec, 40 mins

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: