Search code examples
javascriptdate-fns

Get time difference in seconds, between 2 Epoch times, Javascript


I have 2 Epoch times, e.g. 1673252582, 1673253317

Now i am trying to calculate Difference in seconds between these two using date-fns: differenceInSeconds(1673252582, 1673253317).

But this is giving me -0 as result.

Please help.


Solution

  • You can calculate the diff by subtracting one timestamp from the other.

    If you need it in seconds and current input is in milliseconds, you will need to convert milliseconds to seconds by dividing by 1000.

    for example:

    const diffInSeconds = (timestampA, timestampB) => {
      //  absolute value added incase you just want the diff but don't care which came first
      return (Math.abs(timestampB - timestampA)) / 1000
    }
    
    const res = diffInSeconds(1673256249000, 1673256240000)
    console.log(res) // 9