Javascript返回两个日期之间的天数、小时数、分钟数、秒数 [英] Javascript return number of days,hours,minutes,seconds between two dates
问题描述
有没有人可以将我链接到一些教程,在那里我可以找到如何在 2 个 unix 日期时间之间的 javascript 中返回天、小时、分钟、秒?
Does anyone can link me to some tutorial where I can find out how to return days , hours , minutes, seconds in javascript between 2 unix datetimes?
我有:
var date_now = unixtimestamp;
var date_future = unixtimestamp;
我想返回(实时)从 date_now 到 date_future 还剩多少天、小时、分钟、秒.
I would like to return (live) how many days,hours,minutes,seconds left from the date_now to the date_future.
推荐答案
只需找出秒的差异(别忘了 JS 时间戳实际上是以毫秒为单位测量的)并分解该值:
Just figure out the difference in seconds (don't forget JS timestamps are actually measured in milliseconds) and decompose that value:
// get total seconds between the times
var delta = Math.abs(date_future - date_now) / 1000;
// calculate (and subtract) whole days
var days = Math.floor(delta / 86400);
delta -= days * 86400;
// calculate (and subtract) whole hours
var hours = Math.floor(delta / 3600) % 24;
delta -= hours * 3600;
// calculate (and subtract) whole minutes
var minutes = Math.floor(delta / 60) % 60;
delta -= minutes * 60;
// what's left is seconds
var seconds = delta % 60; // in theory the modulus is not required
EDIT 代码进行了调整,因为我刚刚意识到原始代码返回了总小时数等,而不是计算一整天后剩余的小时数.
EDIT code adjusted because I just realised that the original code returned the total number of hours, etc, not the number of hours left after counting whole days.
这篇关于Javascript返回两个日期之间的天数、小时数、分钟数、秒数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!