Find elapsed time in javascript

前端 未结 9 580
死守一世寂寞
死守一世寂寞 2020-12-10 03:35

I\'m new to JavaScript and I\'m trying to write a code which calculates the time elapsed from the time a user logged in to the current time.

Here is my code:-

9条回答
  •  一个人的身影
    2020-12-10 04:15

    Here is a solution I just made for my use case. I find it is quite readable. The basic premise is to simply subtract the timestamp from the current timestamp, and then divide it by the correct units:

    const showElapsedTime = (timestamp) => {
        if (typeof timestamp !== 'number') return 'NaN'        
    
        const SECOND = 1000
        const MINUTE = 1000 * 60
        const HOUR = 1000 * 60 * 60
        const DAY = 1000 * 60 * 60 * 24
        const MONTH = 1000 * 60 * 60 * 24 * 30
        const YEAR = 1000 * 60 * 60 * 24 * 30 * 12
        
        // const elapsed = ((new Date()).valueOf() - timestamp)
        const elapsed = 1541309742360 - timestamp
        
        if (elapsed <= MINUTE) return `${Math.round(elapsed / SECOND)}s`
        if (elapsed <= HOUR) return `${Math.round(elapsed / MINUTE)}m`
        if (elapsed <= DAY) return `${Math.round(elapsed / HOUR)}h`
        if (elapsed <= MONTH) return `${Math.round(elapsed / DAY)}d`
        if (elapsed <= YEAR) return `${Math.round(elapsed / MONTH)}mo`
        return `${Math.round(elapsed / YEAR)}y`
    }
          
    const createdAt = 1541301301000
    
    console.log(showElapsedTime(createdAt + 5000000))
    console.log(showElapsedTime(createdAt))
    console.log(showElapsedTime(createdAt - 500000000))

    For example, if 3000 milliseconds elapsed, then 3000 is greater than SECONDS (1000) but less than MINUTES (60,000), so this function will divide 3000 by 1000 and return 3s for 3 seconds elapsed.

    If you need timestamps in seconds instead of milliseconds, change all instances of 1000 to 1 (which effectively multiplies everything by 1000 to go from milliseconds to seconds (ie: because 1000ms per 1s).

    Here are the scaling units in more DRY form:

    const SECOND = 1000
    const MINUTE = SECOND * 60
    const HOUR = MINUTE * 60
    const DAY = HOUR * 24
    const MONTH = DAY * 30
    const YEAR = MONTH * 12
    

提交回复
热议问题