admin管理员组

文章数量:1414605

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'".

Share Improve this question asked Jun 7, 2022 at 11:12 kkongkkkkongkk 1072 silver badges8 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

You 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'));

本文标签: javascriptConverting unix timestamp to Milliseconds in luxonjsStack Overflow