I have string data in the format "hh:mm" e.g. 05:00. I want it in Milliseconds e.g 1800000
console.log(DateTime.fromISO("05:00")
and i get the following output: 1654574400000 but what i want it in seconds so i can pare it against a different value. I have tried putting .toMillis() at the end
console.log(DateTime("05:00")).toMillis();
and it es back with "Unhandled Rejection (TypeError): Class constructor DateTime cannot be invoked without 'new'".
I have string data in the format "hh:mm" e.g. 05:00. I want it in Milliseconds e.g 1800000
console.log(DateTime.fromISO("05:00")
and i get the following output: 1654574400000 but what i want it in seconds so i can pare it against a different value. I have tried putting .toMillis() at the end
console.log(DateTime("05:00")).toMillis();
and it es back with "Unhandled Rejection (TypeError): Class constructor DateTime cannot be invoked without 'new'".
2 Answers
Reset to default 3You can parse "05:00"
as a Duration
, using Duration.fromISOTime
that:
Create a Duration from an ISO 8601 time string.
and then display its value using as(unit)
:
Return the length of the duration in the specified unit.
Example:
const Duration = luxon.Duration;
console.log(Duration.fromISOTime('05:00').as('milliseconds'));
<script src="https://cdn.jsdelivr/npm/[email protected]/build/global/luxon.min.js"></script>
When a time is passed to fromISO, the current date is used. To get the time in milliseconds, parse it to a DateTime and subtract a DateTime for the start of the day, e.g.
let DateTime = luxon.DateTime;
function timeToMs(time) {
let then = DateTime.fromISO(time);
let now = DateTime.fromISO("00:00");
return then - now;
}
console.log(timeToMs('05:00'));
<script src="https://cdnjs.cloudflare./ajax/libs/luxon/2.4.0/luxon.min.js"></script>
You can also use plain JS:
function timeToMS(time) {
let [h, m, s, ms] = time.split(/\D/);
return h*3.6e6 + (m||0)*6e4 + (s||0)*1e3 + (ms||0)*1;
}
console.log(timeToMS('05:00'));
console.log(timeToMS('01:01:01.001'));
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745194648a4616031.html
评论列表(0条)