-1

I've been trying to turn the following simple millisecond to "minutes and seconds" conversion into a function. I'd like to use a function so I can easily send the milliseconds as a parameter and then return the formatted minutes and seconds.

const date = new Date(123456);
`${date.getMinutes()} minutes ${date.getSeconds()} seconds`; // Expected result: "2 minutes 3 seconds"

For the life of me I can't figure it out. I'm both seeking a short term solution and also an reason this isn't as simple as it seems, as I'm still very new to learning JavaScript.

CapsaCool
  • 67
  • 5
  • 1
    Do you just want `ms` converted to minutes and seconds? If so using `Date` is not the way to go since it is tracking an offset from a datetime, not a duration. – pilchard Feb 10 '23 at 23:51
  • @pilchard You're correct. I just want `ms` converted into a clean set of minutes and seconds. For example `61123` would return `1 minute 1 second`. – CapsaCool Feb 10 '23 at 23:54
  • 2
    Then it is just a matter of arithmetic as covered in the duplicate :) – pilchard Feb 10 '23 at 23:56
  • 1
    You should definitely **use arithmetic** instead of `Date`. [Leap seconds](https://en.m.wikipedia.org/wiki/Leap_second) _will_ result in a difference between the expected duration and _time_ (of dates). – Oskar Grosser Feb 11 '23 at 01:29

1 Answers1

0

Unless I missed the point, you can wrap it in a function declaration:

function explainTime(milliseconds) {
  const date = new Date(milliseconds);
  return `${date.getMinutes()} minutes ${date.getSeconds()} seconds`;
}

You can then call this function with any number you want:

const time1 = explainTime(1000); // 0 minutes 1 seconds
const time2 = explainTime(66000); // 1 minutes 6 seconds
carlosV2
  • 1,167
  • 6
  • 15
  • If the OP is looking to convert ms to minutes and seconds this won't give the expected results `explainTime(1000 * 60 * 60);` -> `0 minutes 0 seconds` rather than `60 minutes 0 seconds` – pilchard Feb 10 '23 at 23:53
  • This is still very helpful as it solved the issue I had with wrapping it in a function. I had made a very rookie mistake and didn’t see past it until both answers. – CapsaCool Feb 11 '23 at 00:07