1

I currently am using the library dayjs in an application for time tracking. Each user tracks the number of minutes they have worked on an assignment and the total number of minutes worked is stored as an integer. For example, a user who works 2 hours in total will have the total number of minutes worked stored as 120. The result I am trying to produce, is if a user has 120 hours worked I would like to display that back to the user as 02:00. I have achieved this using the following method:

const totalMinutes = 120
const dateObject = dayjs.duration(totalMinutes, 'minutes').$d
 const hoursToString = dateObject.hours.toString()
    const minToString = dateObject.minutes.toString()
    const hours =
      hoursToString.length <= 1
        ? '0' + hoursToString
        : dateObject.hours.toString()
    const minutes = minToString.length <= 1 ? '0' + minToString : minToString
    const finalTime = hours + ':' + minutes


while this method works, I can't help but feel like there's a much more efficient way of tackling this. Attached is a code sandbox for debugging https://codesandbox.io/s/nervous-chatelet-s6vxz?file=/src/App.js any and all suggestions are welcomed!

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Rob Terrell
  • 2,398
  • 1
  • 14
  • 36
  • Does this answer your question? [Convert seconds to HH-MM-SS with JavaScript?](https://stackoverflow.com/questions/1322732/convert-seconds-to-hh-mm-ss-with-javascript) – Heretic Monkey Apr 14 '21 at 15:51
  • 1
    The [Day.js docs](https://day.js.org/docs/en/durations/format) show how to format a duration as HH:mm. – Noleli Apr 14 '21 at 15:54
  • If your code works, and you want a review of all aspects of the code (including "efficiency", performance, etc.), check the [help center](https://codereview.stackexchange.com/help) to see if your question is on topic on [codereview.se]. – Heretic Monkey Apr 14 '21 at 15:54
  • thanks Noleli overlooked this in the dayjs docs – Rob Terrell Apr 14 '21 at 15:58

2 Answers2

0

Thanks to Noleli's suggestion I found dayjs provides a formatting option regarding how to format a duration using dayjs.

const totalMinutes = 120
const finalTime = dayjs.duration(totalMinutes, 'minutes').format('HH:mm')
Rob Terrell
  • 2,398
  • 1
  • 14
  • 36
  • The Problem with this solution is: As soon as the amount of "hours" exceeds 24, dayjs calculates in days which are lost when formatting as 'HH:mm'. Example: `totalMinutes=1530` results in `01:30` but should be `25:30` – ToFi Oct 15 '21 at 09:02
0

You can try to use this

e.g

`const a = 2;

const c= str1.padStart(2, '0'); ` here c equals to "05"

find here the documentation https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/String/padStart