Is there any way I can use the moment.js format
method on duration objects? I can\'t find it anywhere in the docs and it doesn\'t seen to be an attribute on du
If you're willing to use a different javascript library, numeral.js can format seconds as follows (example is for 1000 seconds):
var string = numeral(1000).format('00:00');
// '00:16:40'
Use this line of code:
moment.utc(moment.duration(4500, "seconds").asMilliseconds()).format("HH:mm:ss")
This works for me:
moment({minutes: 150}).format('HH:mm') // 01:30
This can be used to get the first two characters as hours and last two as minutes. Same logic may be applied to seconds.
/**
* PT1H30M -> 0130
* @param {ISO String} isoString
* @return {string} absolute 4 digit number HH:mm
*/
const parseIsoToAbsolute = (isoString) => {
const durations = moment.duration(isoString).as('seconds');
const momentInSeconds = moment.duration(durations, 'seconds');
let hours = momentInSeconds.asHours().toString().length < 2
? momentInSeconds.asHours().toString().padStart(2, '0') : momentInSeconds.asHours().toString();
if (!Number.isInteger(Number(hours))) hours = '0'+ Math.floor(hours);
const minutes = momentInSeconds.minutes().toString().length < 2
? momentInSeconds.minutes().toString().padEnd(2, '0') : momentInSeconds.minutes().toString();
const absolute = hours + minutes;
return absolute;
};
console.log(parseIsoToAbsolute('PT1H30M'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Use this plugin Moment Duration Format.
Example:
moment.duration(123, "minutes").format("h:mm");
How to correctly use moment.js durations? | Use moment.duration() in code
First you need to import moment
and moment-duration-format
.
import moment from 'moment';
import 'moment-duration-format';
Then, use duration function. Let us apply the above example: 28800 = 8 am.
moment.duration(28800, "seconds").format("h:mm a");