以秒为单位获取两个日期之间的时差 [英] Get time difference between two dates in seconds

查看:31
本文介绍了以秒为单位获取两个日期之间的时差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在几秒钟内获得两个日期之间的差异.逻辑是这样的:

I'm trying to get a difference between two dates in seconds. The logic would be like this :

  • 设置一个初始日期,即现在;
  • 设置一个最终日期,即初始日期加上未来的一些秒数(例如 15 秒)
  • 获取两者之间的差异(秒数)

我用日期来做它的原因是因为最终日期/时间取决于其他一些变量并且它永远不会相同(这取决于用户做某事的速度)而且我还存储了初始日期其他事情.

The reason why I'm doing it it with dates it's because the final date / time depends on some other variables and it's never the same ( it depends on how fast a user does something ) and I also store the initial date for other things.

我一直在尝试这样的事情:

I've been trying something like this :

var _initial = new Date(),
    _initial = _initial.setDate(_initial.getDate()),
    _final = new Date(_initial);
    _final = _final.setDate(_final.getDate() + 15 / 1000 * 60);

var dif = Math.round((_final - _initial) / (1000 * 60));

问题是我从来没有得到正确的区别.我尝试除以 24 * 60 这会给我留下秒数,但我从来没有做对.那么我的逻辑有什么问题吗?我可能会犯一些愚蠢的错误,因为它已经很晚了,但我无法让它工作让我感到困扰:)

The thing is that I never get the right difference. I tried dividing by 24 * 60 which would leave me with the seconds, but I never get it right. So what is it wrong with my logic ? I might be making some stupid mistake as it's quite late, but it bothers me that I cannot get it to work :)

推荐答案

代码

var startDate = new Date();
// Do your operations
var endDate   = new Date();
var seconds = (endDate.getTime() - startDate.getTime()) / 1000;

或者更简单的 (endDate - startDate)/1000 如注释中所指出的,除非您使用的是 typescript.

Or even simpler (endDate - startDate) / 1000 as pointed out in the comments unless you're using typescript.

您需要为 Date 对象调用 getTime() 方法,然后简单地减去它们并除以 1000(因为它最初以毫秒为单位).另外,当您调用 getDate() 方法时,实际上是将月份中的某一天作为 1 到 31(不是基于零的)之间的整数而不是纪元您从调用 getTime() 方法中获得的时间,表示自 1970 年 1 月 1 日 00:00

You need to call the getTime() method for the Date objects, and then simply subtract them and divide by 1000 (since it's originally in milliseconds). As an extra, when you're calling the getDate() method, you're in fact getting the day of the month as an integer between 1 and 31 (not zero based) as opposed to the epoch time you'd get from calling the getTime() method, representing the number of milliseconds since January 1st 1970, 00:00

根据您的日期相关操作,您可能希望投资集成一个库,例如 date.jsmoment.js 使开发人员更容易,但这只是个人喜好问题.

Depending on what your date related operations are, you might want to invest in integrating a library such as date.js or moment.js which make things so much easier for the developer, but that's just a matter of personal preference.

例如在 moment.js 中,我们会做 moment1.diff(moment2, "seconds") 很漂亮.

For example in moment.js we would do moment1.diff(moment2, "seconds") which is beautiful.

这篇关于以秒为单位获取两个日期之间的时差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆