Javascript 以秒为单位获取两个日期之间的时差
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13894632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get time difference between two dates in seconds
提问by Roland
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 )
- get the difference between those two ( the amount of seconds )
- 设置一个初始日期,即现在;
- 设置一个最终日期,这将是初始日期加上未来的一些秒数(例如 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));
The thing is that I never get the right difference. I tried dividing by 24 * 60which 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哪个会给我留下秒数,但我从来没有做对。那么我的逻辑有什么问题吗?我可能会犯一些愚蠢的错误,因为已经很晚了,但是我无法让它工作让我很困扰:)
回答by Juan Cortés
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) / 1000as pointed out in the comments unless you're using typescript.
或者甚至(endDate - startDate) / 1000如评论中指出的那样更简单,除非您使用打字稿。
The explanation
说明
You need to call the getTime()method for the Dateobjects, 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
您需要调用对象的getTime()方法Date,然后简单地减去它们并除以 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.jsor moment.jswhich make things so much easierfor the developer, but that's just a matter of personal preference.
根据您的日期相关操作,您可能希望投资集成诸如date.js或moment.js 之类的库,这使开发人员的工作变得更加轻松,但这只是个人喜好的问题。
For example in moment.jswe would do moment1.diff(moment2, "seconds")which is beautiful.
例如,在moment.js 中,我们会这样做moment1.diff(moment2, "seconds")很漂亮。
Useful docs for this answer
此答案的有用文档
回答by Abdulrahman A Alkhodairi
<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>
回答by Georgian-Sorin Maxim
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 msinto s.
您可以new 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);
回答by Gautam Rai
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 );
回答by Gilbert Cut
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);
回答by Surya Singh
time difference between now and 10 minutes later using momentjs
现在和 10 分钟后使用 momentjs 的时差
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;

