将UNIX时间戳转换为Luxon.js中的毫秒

发布于 2025-02-05 18:55:35 字数 269 浏览 3 评论 0原文

我有“ HH:MM”格式的字符串数据,例如05:00。我想要它在毫秒中,例如1800000

console.log(dateTime.fromiso(“ 05:00”),我得到以下输出:16545744400000,但是我想要几秒钟的时间,以便我可以将其与A相比,不同的价值。 console.log(dateTime(“ 05:00”))。tomillis(); 它带有“未经手的拒绝(TypeError):如果没有'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 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'".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

九命猫 2025-02-12 18:55:36

当时间传递到 fromiso 时,使用当前日期。要使时间以毫秒为单位,请将其解析为a datetime 并在一天开始时减去 dateTime

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>

您也可以使用普通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'));

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

乖乖哒 2025-02-12 18:55:35

您可以解析“ 05:00”作为 持续时间 ,使用持续时间。fromisotime 那就是:

从ISO 8601时字符串创建持续时间。

然后使用 as(unit)

返回指定单元中持续时间的长度。

例子:

const Duration = luxon.Duration;
console.log(Duration.fromISOTime('05:00').as('milliseconds'));
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/global/luxon.min.js"></script>

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.net/npm/[email protected]/build/global/luxon.min.js"></script>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文