简体   繁体   English

moment js:自定义格式的字符串到天的持续时间

[英]moment js: custom format string to day duration

I'm have a rather wiered string with time. 我的时间有些混乱。 Something like this - "2.23:59:59.99" . 这样的东西- "2.23:59:59.99" That means that first number before dot is a day count (2 days) and other is a time count - 23 hours 59 minutes 59 seconds and 9900 - milliseconds (or maybe 99 milliseconds). 这意味着点之前的第一个数字是天数(2天),另一个是时间数-23小时59分59秒和9900毫秒(或可能是99毫秒)。 So I need to convert it to decimal number, like 2.99 . 所以我需要将其转换为十进制数,例如2.99 How can I do it using moment.js ? 如何使用moment.js进行操作?

You can simply create a moment duration from your "2.23:59:59.99" string 您只需从"2.23:59:59.99"字符串创建一个持续时间

As of 2.1.0 , moment supports parsing ASP.NET style time spans. 2.1.0版本开始 ,时刻支持解析ASP.NET样式时间跨度。 The following formats are supported. 支持以下格式。

The format is an hour, minute, second string separated by colons like 23:59:59 . 格式是小时,分钟,第二个字符串,中间用冒号分隔,例如23:59:59 The number of days can be prefixed with a dot separator like so 7.23:59:59 . 天数可以加上点分隔符,例如7.23:59:59 Partial seconds are supported as well 23:59:59.999 . 同时支持部分秒23:59:59.999

and then get its values in days using asDays() 然后使用asDays()以天为单位获取其值

moment.duration().asDays() gets the length of the duration in days. moment.duration().asDays()以天为单位获取持续时间的长度。


To get "2.23:59:59.99" back from 2.99 , you can create a duration using moment.duration(Number, String) and use format() method of moment-duration-format plug-in (using precision parameter) 要从2.99返回"2.23:59:59.99" ,可以使用moment.duration(Number, String)创建一个持续时间moment.duration(Number, String)并使用moment-duration-format插件的format()方法(使用precision参数)

 // 2.23:59:59.99 to 2.99 const dur1 = moment.duration("2.23:59:59.99"); const durAsDays = dur1.asDays(); console.log(durAsDays); // 2.99 to 2.23:59:59.99 const dur2 = moment.duration(durAsDays, 'days'); console.log(dur2.format("d.HH:mm:ss", 2)); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/2.2.2/moment-duration-format.min.js"></script> 

moment.duration('2.23:59:59.99').asDays() 

请参考Moment JS .asDays()方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM