我正在尝试将像 1.25 这样的小数格式化为如下格式。
我正在使用 FullCalendar。
我想做的是从日历中删除事件,但将它们放回具有适当的 data-duration
属性的外部事件队列中。
1 -> 01:00
1.25 -> 01:15
1.5 -> 01:30
1.75 -> 01:45
等等
我将始终只以 15 分钟的间隔工作。
这可以用 moment.js 实现吗?
谢谢!
最佳答案
我认为 momentjs 对于这个简单的目的来说有点矫枉过正。 您可能想使用 vanilla JS 来获取以这种方式格式化的小数
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'
一些解释:
!
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;
关于javascript - Moment.js小数转时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33769178/