简体   繁体   中英

moment js function to show duration in human readable format like (5 hours and 10 minutes) from number of seconds

Is there any function available in moment.js to convert seconds into human readable duration like for 3720 seconds it should show 1 Hours and 2 minutes .

I know this can be easily done with simple math operations like % and / , but i am searching if any moment.js function available for it.

I'd suggest trying moment duration format , this gives you a lot of options:

 console.log("Duration (123 sec):", moment.duration(123, "seconds").format("mm:ss")); console.log("Duration (350 sec):", moment.duration(350, "seconds").format("m [minutes] [and] s [seconds]")); console.log("Duration (3720 seconds):", moment.duration(3720, "seconds").format("h [hours] [and] m [minutes]"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/2.3.2/moment-duration-format.js"></script>

I'd also consider using Luxon , this will give you the ability to format dates too:

 const { Duration } = luxon; console.log(Duration.fromObject({ seconds: 3720 }).toFormat("h 'hours and' m 'minutes'"))
 <script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/1.25.0/luxon.min.js" integrity="sha512-OyrI249ZRX2hY/1CAD+edQR90flhuXqYqjNYFJAiflsKsMxpUYg5kbDDAVA8Vp0HMlPG/aAl1tFASi1h4eRoQw==" crossorigin="anonymous"></script>

As others have noted, moment.js is in maintenance mode (see project-status ), so you might consider using luxon instead (or another library)

 const { Duration } = luxon; console.log(Duration.fromObject({ seconds: 37200 }).toFormat("h 'hours and' m 'minutes'"))
 <script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/1.25.0/luxon.min.js" integrity="sha512-OyrI249ZRX2hY/1CAD+edQR90flhuXqYqjNYFJAiflsKsMxpUYg5kbDDAVA8Vp0HMlPG/aAl1tFASi1h4eRoQw==" crossorigin="anonymous"></script>

c

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