Home > OS >  Turn difference of dates in javascript in format of minutes with seconds
Turn difference of dates in javascript in format of minutes with seconds

Time:08-05

I made a game model that creates a starting point of game and a ending point of game:
gameStart: 2022-08-03T19:18:07.279Z
gameEnd: 2022-08-03T19:20:09.931Z

I want to find the difference of two dates that displays it in this format:
x minutes and y seconds

example: 4 minutes and 25 seconds

How can I do this in JavaScript?

CodePudding user response:

You can use a library like moment.js or use plain JavaScript like below:

const getSeconds = (dateString) => new Date(dateString).getTime() / 1000

const gameStart = getSeconds("2022-08-03T19:18:07.279Z")
const gameEnd = getSeconds("2022-08-03T19:20:09.931Z")

const diff = (gameEnd - gameStart)
const minutes = Math.floor(diff / 60);
const seconds = Math.floor(diff % 60); 

console.log(`${minutes} minutes and ${seconds} seconds`)

CodePudding user response:

I think you should use date-fns for that, they have a lot of methods to return the difference between two dates!

Check out those two:

https://date-fns.org/v2.29.1/docs/differenceInMinutes

https://date-fns.org/v2.29.1/docs/differenceInSeconds

  • Related