Reputation: 1272
I'm have a rather wiered string with time. Something like this - "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). So I need to convert it to decimal number, like 2.99
. How can I do it using moment.js ?
Upvotes: 0
Views: 874
Reputation: 31482
You can simply create a moment duration from your "2.23:59:59.99"
string
As of 2.1.0, moment supports parsing ASP.NET style time spans. The following formats are supported.
The format is an hour, minute, second string separated by colons like
23:59:59
. The number of days can be prefixed with a dot separator like so7.23:59:59
. Partial seconds are supported as well23:59:59.999
.
and then get its values in days using asDays()
moment.duration().asDays()
gets the length of the duration in days.
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.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>
Upvotes: 3
Reputation: 1067
moment.duration('2.23:59:59.99').asDays()
Refer to Moment JS .asDays() method
Upvotes: 0