简体   繁体   中英

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

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
}

you can use something like this

import React from 'react';
import { DateTime } from 'luxon';

function secondsToHMS(seconds) {
  const duration = DateTime.fromMillis(seconds * 1000);
  return duration.toFormat('hh:mm:ss');
}

function App() {
  return (
    <div>
      <p>{secondsToHMS(3661)}</p>
    </div>
  );
}```
And if you want to custom the format you could do something like
```javascript
return duration.toFormat('hh hours, mm minutes and ss seconds');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM