最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Moment.js decimals into time format - Stack Overflow

programmeradmin6浏览0评论

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 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!

Share Improve this question asked Nov 17, 2015 at 23:38 stillfirestillfire 2093 silver badges9 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

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;

Here's a simple function with momentJS

 const formatTime = (time: number) => {
    const duration = moment.duration(time, 'hours');
    const hours = duration?.get('hours');
    const minutes = duration?.get('minutes');
    return `${hours}`.padStart(2, '0') + ':' + `${minutes}`.padStart(2, '0');
  };

formatTime(7.5) //Output 07:30
发布评论

评论列表(0)

  1. 暂无评论