I am trying to format a decimal like 1.25 into a format as follows.
I am working with FullCalendar.
What I am trying to do is remove events from the calendar, but place them back into the external events queue with proper data-duration
attribute.
1 -> 01:00
1.25 -> 01:15
1.5 -> 01:30
1.75 -> 01:45
etc.
I will always only be working in 15 minute intervals.
Is this possible with moment.js?
Thanks!
I assume that momentjs would be an overkill for this simple purpose. You may want to use vanilla JS to get decimals formatted in that fashion
function parse(num) {
return ('0' + Math.floor(num) % 24).slice(-2) + ':' + ((num % 1)*60 + '0').slice(0, 2);
}
parse(24.5) -> '00:30'
parse(1.25) -> '01:15'
parse(1.5) -> '01:30'
parse(1.75) -> '01:45'
Some explanation:
!
Math.floor(num) % 24
- get amount of hours!
'0'
+ Math.floor(num) % 24
- coerce number to string with leading nil!
('0' + Math.floor(num) % 24)
.slice(-2)
- get last two chars in string!
(num % 1)
- get minutes as part of decimal fraction!
(num % 1)
* 60 + '0'
- coerce to minutes with trailing nil!
(num % 1)*60 + '0')
.slice(0, 2)
- get first two chars in string;