简体   繁体   中英

Moment.js returning 2 days if duration is 24 hours

I need to have a function where the user can insert a certain timeframe (eg 1 week or 5 days and 12 hours). Duration from Moment.js looked the most promising.

The code below returns 2 00:00 , where 2 equals the numbers of days. This should be 1 because there are only 24 hours in there.

moment.utc(moment.duration(24, 'hours').as("milliseconds")).format("D HH:mm");

What am I doing wrong here?

You are setting 24 hours as a millisecond offset from 1970-01-01 (Unix epoch) by calling moment.utc(...) . This means that your moment is holding the date 1970-01-02 00:00 and you are then printing the day part.

If the time frames are fixed and set by yourself you could always manually put in the amount of time in milliseconds to start with. eg 24 hours is 86400000 milliseconds.

You have to format the milliseconds in moment duration not in moment. I think the below line gives your expected value.

 moment.duration(moment.duration(24, 'hours').as("milliseconds")).format("D HH:mm");

Answer : 1 00:00

我通过以下代码和插件对其进行了修复:

moment.duration(moment().diff(moment().subtract(1, 'days')));

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