Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

example:
4 minutes and 25 seconds

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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`)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading