Search code examples
javascriptreactjstimeconvertersluxon

how to correctly converter seconds to minute/hour with luxon ReactJs


I would like to explain my problem of the day.

currently I have a function that works correctly

function numberToHms(numbers) {
  let hms;
  let number = numbers;
  number = Number(number);

  const h = Math.floor(number / 3600);
  const m = Math.floor((number % 3600) / 60);
  const s = Math.floor((number % 3600) % 60);

    const hour =
         h > 0
             ? `${h}h`
             : "";

     const minute =
         m > 0
             ? `${m}min`
             : "";

    const second =
         s > 0
             ? `${s}${
                   m === 0 && h === 0
                       ? `seconde`
                       : `sec`
             : "";

     if (h > 0) {
         hms = hour + minute;
     }

     if (m > 0 && h === 0) {
         hms = minute + second;
     }

    if (s > 0 && m === 0 && h === 0) {
         hms = second;
     }

     return hms;
 }

render

<p>{numberToHms(24)}</p>

so my problem and the next one I would like to replace this function to use luxon directly

if you have any ideas, thank you

Neff


Solution

  • function numberToHms(number) {
    
    const duration = Duration.fromObject({ seconds: number});
    
    const minutesSeconds = duration.toFormat('mm:ss'); //to convert it to Hours minutes and seconds use this duration.toFormat('hh:mm:ss');
    console.log(minutesSeconds);
    
    return minutesSeconds
    }