Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

javascript timestamp to relative time

function timeDifference(current, previous) {

    var msPerMinute = 60 * 1000;
    var msPerHour = msPerMinute * 60;
    var msPerDay = msPerHour * 24;
    var msPerMonth = msPerDay * 30;
    var msPerYear = msPerDay * 365;

    var elapsed = current - previous;

    if (elapsed < msPerMinute) {
         return Math.round(elapsed/1000) + ' seconds ago';   
    }

    else if (elapsed < msPerHour) {
         return Math.round(elapsed/msPerMinute) + ' minutes ago';   
    }

    else if (elapsed < msPerDay ) {
         return Math.round(elapsed/msPerHour ) + ' hours ago';   
    }

    else if (elapsed < msPerMonth) {
        return 'approximately ' + Math.round(elapsed/msPerDay) + ' days ago';   
    }

    else if (elapsed < msPerYear) {
        return 'approximately ' + Math.round(elapsed/msPerMonth) + ' months ago';   
    }

    else {
        return 'approximately ' + Math.round(elapsed/msPerYear ) + ' years ago';   
    }
}
Comment

PREVIOUS NEXT
Code Example
Javascript :: javascript detect click outside of element 
Javascript :: scroll to a tag javascript 
Javascript :: instalar react native paper 
Javascript :: intersection and difference in javascript 
Javascript :: TypeError: date.getHours is not a function 
Javascript :: React + modal: input field auto focus 
Javascript :: nodejs copy to clipboard 
Javascript :: js create element 
Javascript :: specify parameter type in javascript vscode 
Javascript :: To install the latest version of React: 
Javascript :: insertion sort javascript 
Javascript :: chart.js hide bar title 
Javascript :: favicon in next js not working 
Javascript :: js get number from string 
Javascript :: how to get domain name in react 
Javascript :: get the domain name in javascript 
Javascript :: javascript get all script tags on page 
Javascript :: string to int javascript 
Javascript :: moment format 23 hour 
Javascript :: remove whitespace with regex javascript 
Javascript :: lodash combine permissions 
Javascript :: js input text set value 
Javascript :: html loop through array 
Javascript :: how to remove id in jquery 
Javascript :: requirenativecomponent rnsscreen was not found in the uimanager 
Javascript :: react native get numeric random string length of 5 characters 
Javascript :: jest test array of objects 
Javascript :: once content is loaded run part of code 
Javascript :: jquery check input is disable 
Javascript :: validar solo letras js 
ADD CONTENT
Topic
Content
Source link
Name
8+1 =