0

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?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
ermir
  • 457
  • 1
  • 3
  • 11
  • 1
    Does this answer your question? [Difference between two dates in years, months, days in JavaScript](https://stackoverflow.com/questions/17732897/difference-between-two-dates-in-years-months-days-in-javascript) – Heretic Monkey Aug 04 '22 at 21:10
  • It contained a solution, but i got a better solution from an answer, i only asked to be converted in minutes and seconds, not in days, month, years etc.. – ermir Aug 04 '22 at 22:09
  • Obviously a solution custom crafted for you is better for you. But Stack Overflow isn't here for you. It's for all developers, and the answers to that question answer this question; you can simply leave off the parts you don't want. – Heretic Monkey Aug 04 '22 at 22:14

2 Answers2

1

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`)
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
wardialer
  • 490
  • 3
  • 7
  • Thank you for response, i will check it out. – ermir Aug 04 '22 at 21:17
  • FYI `moment` is no longer under development. Consider an alternative like `daysjs` if you need to do more date manipulation. It's also a smaller package. – Slbox Aug 04 '22 at 22:37
-1

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

  • Please do not post links to documentation. Instead, show how to use the library with actual code demonstrating how to solve the problem. Of course, this question is asked once a month on this site, so you should really look for duplicates before answering. – Heretic Monkey Aug 04 '22 at 21:12
  • Answers that are just suggestions to use a particular library aren't particularly helpful. It might be useful as a comment. – RobG Aug 05 '22 at 05:14