Home > Net >  Converting unix timestamp to Milliseconds in luxon.js
Converting unix timestamp to Milliseconds in luxon.js

Time:06-08

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 compare it against a different value. I have tried putting .toMillis() at the end console.log(DateTime("05:00")).toMillis(); and it comes back with "Unhandled Rejection (TypeError): Class constructor DateTime cannot be invoked without 'new'".

CodePudding user response:

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.com/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'));

CodePudding user response:

Have you tried .ts at the end and formatting

  • Related