获取两个日期之间的时差,以秒为单位

时间:2021-11-20 16:24:49

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

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

  • set an initial date which would be now;
  • 设定一个现在的初始日期;
  • set a final date which would be the initial date plus some amount of seconds in future ( let's say 15 for instance )
  • 设置一个最终日期,这个日期将是初始日期加上未来的一些秒数(例如,假设为15)
  • get the difference between those two ( the amount of seconds )
  • 得到这两者之间的差异(秒数)

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

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 :)

问题是我从来没有得到正确的区别。我尝试用24 * 60分开,这会留给我秒,但我从来没有做对。那么我的逻辑有什么不对?我可能会犯一些愚蠢的错误,因为它已经很晚了,但令我烦恼的是我无法让它工作:)

6 个解决方案

#1


155  

The Code

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

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

甚至比评论中指出的更简单(endDate - startDate)/ 1000,除非你使用的是打字稿。


The explanation

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对象调用getTime()方法,然后简单地减去它们并除以1000(因为它最初以毫秒为单位)。作为一个额外的,当你调用getDate()方法时,你实际上是将月中的某一天作为1到31之间的整数(不是基于零)而不是你从调用中得到的纪元时间getTime()方法,表示自1970年1月1日00:00以来的毫秒数


Rant

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.

根据您的日期相关操作,您可能希望投资集成诸如date.js或moment.js之类的库,这使得开发人员更容易,但这只是个人偏好的问题。

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

例如在moment.js中我们会做一些很漂亮的moment1.diff(moment2,“秒”)。


Useful docs for this answer

#2


3  

<script type="text/javascript">
var _initial = '2015-05-21T10:17:28.593Z';
var fromTime = new Date(_initial);
var toTime = new Date();

var differenceTravel = toTime.getTime() - fromTime.getTime();
var seconds = Math.floor((differenceTravel) / (1000));
document.write('+ seconds +');
</script>

#3


1  

You can use new Date().getTime() for getting timestamps. Then you can calculate the difference between end and start and finally transform the timestamp which is ms into s.

您可以使用新的Date()。getTime()来获取时间戳。然后你可以计算结束和开始之间的差异,最后将ms的时间戳转换为s。

const start = new Date().getTime();
const end = new Date().getTime();

const diff = end - start;
const seconds = Math.floor(diff / 1000 % 60);

#4


0  

try using dedicated functions from high level programming languages. JavaScript .getSeconds(); suits here:

尝试使用高级编程语言的专用函数。 JavaScript .getSeconds();适合这里:

var specifiedTime = new Date("November 02, 2017 06:00:00");
var specifiedTimeSeconds = specifiedTime.getSeconds(); 

var currentTime = new Date();
var currentTimeSeconds = currentTime.getSeconds(); 

alert(specifiedTimeSeconds-currentTimeSeconds);

#5


0  

time difference between now and 10 minutes later using momentjs

使用momentjs在现在和10分钟之间的时间差

let start_time = moment().format('YYYY-MM-DD HH:mm:ss');
let next_time = moment().add(10, 'm').format('YYYY-MM-DD HH:mm:ss');

let diff_milliseconds = Date.parse(next_time) - Date.parse(star_time);
let diff_seconds = diff_milliseconds * 1000;

#6


0  

Below code will give the time difference in second.

下面的代码将给出秒的时差。

    var date1 = new Date(); // current date
    var date2 = new Date("06/26/2018"); // mm/dd/yyyy format
    var timeDiff = Math.abs(date2.getTime() - date1.getTime()); // in miliseconds
    var timeDiffInSecond = Math.ceil(timeDiff / 1000); // in second

    alert(timeDiffInSecond );

#1


155  

The Code

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

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

甚至比评论中指出的更简单(endDate - startDate)/ 1000,除非你使用的是打字稿。


The explanation

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对象调用getTime()方法,然后简单地减去它们并除以1000(因为它最初以毫秒为单位)。作为一个额外的,当你调用getDate()方法时,你实际上是将月中的某一天作为1到31之间的整数(不是基于零)而不是你从调用中得到的纪元时间getTime()方法,表示自1970年1月1日00:00以来的毫秒数


Rant

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.

根据您的日期相关操作,您可能希望投资集成诸如date.js或moment.js之类的库,这使得开发人员更容易,但这只是个人偏好的问题。

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

例如在moment.js中我们会做一些很漂亮的moment1.diff(moment2,“秒”)。


Useful docs for this answer

#2


3  

<script type="text/javascript">
var _initial = '2015-05-21T10:17:28.593Z';
var fromTime = new Date(_initial);
var toTime = new Date();

var differenceTravel = toTime.getTime() - fromTime.getTime();
var seconds = Math.floor((differenceTravel) / (1000));
document.write('+ seconds +');
</script>

#3


1  

You can use new Date().getTime() for getting timestamps. Then you can calculate the difference between end and start and finally transform the timestamp which is ms into s.

您可以使用新的Date()。getTime()来获取时间戳。然后你可以计算结束和开始之间的差异,最后将ms的时间戳转换为s。

const start = new Date().getTime();
const end = new Date().getTime();

const diff = end - start;
const seconds = Math.floor(diff / 1000 % 60);

#4


0  

try using dedicated functions from high level programming languages. JavaScript .getSeconds(); suits here:

尝试使用高级编程语言的专用函数。 JavaScript .getSeconds();适合这里:

var specifiedTime = new Date("November 02, 2017 06:00:00");
var specifiedTimeSeconds = specifiedTime.getSeconds(); 

var currentTime = new Date();
var currentTimeSeconds = currentTime.getSeconds(); 

alert(specifiedTimeSeconds-currentTimeSeconds);

#5


0  

time difference between now and 10 minutes later using momentjs

使用momentjs在现在和10分钟之间的时间差

let start_time = moment().format('YYYY-MM-DD HH:mm:ss');
let next_time = moment().add(10, 'm').format('YYYY-MM-DD HH:mm:ss');

let diff_milliseconds = Date.parse(next_time) - Date.parse(star_time);
let diff_seconds = diff_milliseconds * 1000;

#6


0  

Below code will give the time difference in second.

下面的代码将给出秒的时差。

    var date1 = new Date(); // current date
    var date2 = new Date("06/26/2018"); // mm/dd/yyyy format
    var timeDiff = Math.abs(date2.getTime() - date1.getTime()); // in miliseconds
    var timeDiffInSecond = Math.ceil(timeDiff / 1000); // in second

    alert(timeDiffInSecond );