Turn difference of dates in javascript in format of minutes with seconds

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

4 minutes and 25 seconds

How can I do this in JavaScript?

>Solution :

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`)

Leave a Reply