如何使用 moment.js 查找以秒为单位的时差

发布于 01-12 23:17 字数 468 浏览 3 评论 0原文

如何找到两个不同时区之间的时差(以秒为单位)。 我想利用这个时间 - 我的开始时间类似于 - 2022-09-04T07:29:39Z[UTC] ,结束时间将是我前端的当前时间。

我的代码 =

 var now  = new Date().getTime();
 var then = "2022-03-04T07:29:39Z[UTC]";
 var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss")); //NAN
 var d = moment.duration(ms);
 var s = d.format("hh:mm:ss");
 console.log("Time Difference =",s);

我需要这方面的帮助,目前我收到 ms 作为 NAN 我该如何纠正它!

How can I find time difference in seconds between two different timezones.
I want to use moment for this -
My start time is something like- 2022-09-04T07:29:39Z[UTC] and end time will be the current time in my frontend.

My code =

 var now  = new Date().getTime();
 var then = "2022-03-04T07:29:39Z[UTC]";
 var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss")); //NAN
 var d = moment.duration(ms);
 var s = d.format("hh:mm:ss");
 console.log("Time Difference =",s);

I need help in this, currently I am getting ms as NAN how can I correct it!

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

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

发布评论

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

评论(2

时常饿2025-01-19 23:17:14

这种类型的计算可以使用 Vanilla JavaScript 轻松完成:

 const now  = new Date().getTime(),
  then = new Date("2022-03-04T07:29:39Z"),
  tsec= Math.round((now-then)/1000),
  sec=tsec%60, tmin=(tsec-sec)/60,
  min=tmin%60, th=(tmin-min)/60,
  h=th%24, d=(th-h)/24;
 
 console.log(`Time Difference = ${d}d ${h}h ${min}m ${sec}s`);

This type of calculation can easily be done with Vanilla JavaScript:

 const now  = new Date().getTime(),
  then = new Date("2022-03-04T07:29:39Z"),
  tsec= Math.round((now-then)/1000),
  sec=tsec%60, tmin=(tsec-sec)/60,
  min=tmin%60, th=(tmin-min)/60,
  h=th%24, d=(th-h)/24;
 
 console.log(`Time Difference = ${d}d ${h}h ${min}m ${sec}s`);

Smile简单爱2025-01-19 23:17:14

d.format 不是 momentjs 公开的函数,您应该像下面这样编写

var now  = new Date().getTime();
var then = "2022-03-04T07:29:39Z[UTC]";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss")); 
var d = moment.duration(ms);
var s = moment(d).format('hh:mm:ss')
console.log("Time Difference =",s);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

d.format is not a function exposed by momentjs instead of that you should write like below

var now  = new Date().getTime();
var then = "2022-03-04T07:29:39Z[UTC]";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss")); 
var d = moment.duration(ms);
var s = moment(d).format('hh:mm:ss')
console.log("Time Difference =",s);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

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