Javascript Javascript返回两个日期之间的天数、小时数、分钟数、秒数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13903897/
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
Javascript return number of days,hours,minutes,seconds between two dates
提问by itsme
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?
有没有人可以将我链接到一些教程,在那里我可以找到如何在 2 个 unix 日期时间之间的 javascript 中返回天数、小时数、分钟数、秒数?
I have:
我有:
var date_now = unixtimestamp;
var date_future = unixtimestamp;
I would like to return (live) how many days,hours,minutes,seconds left from the date_now to the date_future.
我想返回(实时)从 date_now 到 date_future 还剩多少天、小时、分钟、秒。
回答by Alnitak
Just figure out the difference in seconds (don't forget JS timestamps are actually measured in milliseconds) and decompose that value:
只需找出以秒为单位的差异(不要忘记 JS 时间戳实际上以毫秒为单位)并分解该值:
// 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
EDITcode 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.
编辑代码进行了调整,因为我刚刚意识到原始代码返回了总小时数等,而不是计算一整天后剩余的小时数。
回答by Hymancogdill
Here's in javascript: (For example, the future date is New Year's Day)
这是在javascript中:(例如,未来的日期是元旦)
DEMO(updates every second)
DEMO(每秒更新一次)
var dateFuture = new Date(new Date().getFullYear() +1, 0, 1);
var dateNow = new Date();
var seconds = Math.floor((dateFuture - (dateNow))/1000);
var minutes = Math.floor(seconds/60);
var hours = Math.floor(minutes/60);
var days = Math.floor(hours/24);
hours = hours-(days*24);
minutes = minutes-(days*24*60)-(hours*60);
seconds = seconds-(days*24*60*60)-(hours*60*60)-(minutes*60);
回答by RienNeVaPlu?s
I call it the "snowman-carl ? method" and I think it's a little more flexible when you need additional timespans like weeks, moths, years, centuries...and don't want too much repetitive code:
我称之为“雪人卡尔?方法”,我认为当您需要额外的时间跨度(如周、飞蛾、年、世纪……)并且不想要太多重复代码时,它会更灵活一些:
var d = Math.abs(date_future - date_now) / 1000; // delta
var r = {}; // result
var s = { // structure
year: 31536000,
month: 2592000,
week: 604800, // uncomment row to ignore
day: 86400, // feel free to add your own row
hour: 3600,
minute: 60,
second: 1
};
Object.keys(s).forEach(function(key){
r[key] = Math.floor(d / s[key]);
d -= r[key] * s[key];
});
// for example: {year:0,month:0,week:1,day:2,hour:34,minute:56,second:7}
console.log(r);
Have a FIDDLE/ ES6 Version (2018)/ TypeScript Version (2019)
有 FIDDLE/ ES6 Version (2018)/TypeScript Version (2019)
Inspired by Alnitak's answer.
灵感来自Alnitak的回答。
回答by csg
Please note that calculating only based on differences will not cover all cases: leap years and switching of "daylight savings time".
请注意,仅基于差异的计算不会涵盖所有情况:闰年和“夏令时”的切换。
Javascript has poor built-in library for working with dates. I suggest you use a third party javascript library, e.g. MomentJS; you can see herethe function you were looking for.
Javascript 用于处理日期的内置库很差。我建议您使用第三方 javascript 库,例如MomentJS;你可以在这里看到你正在寻找的功能。
回答by CisSasGot
my solution is not as clear as that, but I put it as another example
我的解决方案没有那么清楚,但我把它作为另一个例子
console.log(duration('2019-07-17T18:35:25.235Z', '2019-07-20T00:37:28.839Z'));
function duration(t0, t1){
let d = (new Date(t1)) - (new Date(t0));
let weekdays = Math.floor(d/1000/60/60/24/7);
let days = Math.floor(d/1000/60/60/24 - weekdays*7);
let hours = Math.floor(d/1000/60/60 - weekdays*7*24 - days*24);
let minutes = Math.floor(d/1000/60 - weekdays*7*24*60 - days*24*60 - hours*60);
let seconds = Math.floor(d/1000 - weekdays*7*24*60*60 - days*24*60*60 - hours*60*60 - minutes*60);
let milliseconds = Math.floor(d - weekdays*7*24*60*60*1000 - days*24*60*60*1000 - hours*60*60*1000 - minutes*60*1000 - seconds*1000);
let t = {};
['weekdays', 'days', 'hours', 'minutes', 'seconds', 'milliseconds'].forEach(q=>{ if (eval(q)>0) { t[q] = eval(q); } });
return t;
}
回答by Ohad Schneider
The best library that I know of for duration breakdown is countdown.js. It handles all the hard cases such as leap years and daylight savings as csg mentioned, and even allows you to specify fuzzy concepts such as months and weeks. Here's the code for your case:
我所知道的最好的持续时间分解库是countdown.js。它可以处理csg 提到的所有困难情况,例如闰年和夏令时,甚至允许您指定月和周等模糊概念。这是您的案例的代码:
//assuming these are in *seconds* (in case of MS don't multiply by 1000 below)
var date_now = 1218374;
var date_future = 29384744;
diff = countdown(date_now * 1000, date_future * 1000,
countdown.DAYS | countdown.HOURS | countdown.MINUTES | countdown.SECONDS);
alert("days: " + diff.days + " hours: " + diff.hours +
" minutes: " + diff.minutes + " seconds: " + diff.seconds);
//or even better
alert(diff.toString());
Here's a JSFiddle, but it would probably only work in FireFox or in Chrome with web security disabled, since countdown.js is hosted with a text/plainMIME type (you're supposed to serve the file, not link to countdownjs.org).
这是一个JSFiddle,但它可能只能在禁用网络安全的 FireFox 或 Chrome 中工作,因为 countdown.js 是用文本/纯MIME 类型托管的(您应该提供文件,而不是链接到 countdownjs.org) .
回答by Sceptic
Here is a code example. I used simple calculations instead of using precalculations like 1 day is 86400 seconds. So you can follow the logic with ease.
这是一个代码示例。我使用了简单的计算,而不是使用预计算,比如 1 天是 86400 秒。所以你可以轻松地遵循逻辑。
// Calculate time between two dates:
var date1 = new Date('1110-01-01 11:10');
var date2 = new Date();
console.log('difference in ms', date1 - date2);
// Use Math.abs() so the order of the dates can be ignored and you won't
// end up with negative numbers when date1 is before date2.
console.log('difference in ms abs', Math.abs(date1 - date2));
console.log('difference in seconds', Math.abs(date1 - date2) / 1000);
var diffInSeconds = Math.abs(date1 - date2) / 1000;
var days = Math.floor(diffInSeconds / 60 / 60 / 24);
var hours = Math.floor(diffInSeconds / 60 / 60 % 24);
var minutes = Math.floor(diffInSeconds / 60 % 60);
var seconds = Math.floor(diffInSeconds % 60);
var milliseconds = Math.round((diffInSeconds - Math.floor(diffInSeconds)) * 1000);
console.log('days', days);
console.log('hours', ('0' + hours).slice(-2));
console.log('minutes', ('0' + minutes).slice(-2));
console.log('seconds', ('0' + seconds).slice(-2));
console.log('milliseconds', ('00' + milliseconds).slice(-3));
回答by ns16
回答by icl7126
Short and flexible with support for negative values, although by using two comma expressions :)
简短而灵活,支持负值,尽管使用两个逗号表达式:)
function timeUnitsBetween(startDate, endDate) {
let delta = Math.abs(endDate - startDate) / 1000;
const isNegative = startDate > endDate ? -1 : 1;
return [
['days', 24 * 60 * 60],
['hours', 60 * 60],
['minutes', 60],
['seconds', 1]
].reduce((acc, [key, value]) => (acc[key] = Math.floor(delta / value) * isNegative, delta -= acc[key] * isNegative * value, acc), {});
}
Example:
例子:
timeUnitsBetween(new Date("2019-02-11T02:12:03+00:00"), new Date("2019-02-11T01:00:00+00:00"));
// { days: -0, hours: -1, minutes: -12, seconds: -3 }
Inspired by RienNeVaPlu?ssolution.
灵感来自RienNeVaPlu 的解决方案。
回答by M Arfan
function update(datetime = "2017-01-01 05:11:58") {
var theevent = new Date(datetime);
now = new Date();
var sec_num = (theevent - now) / 1000;
var days = Math.floor(sec_num / (3600 * 24));
var hours = Math.floor((sec_num - (days * (3600 * 24)))/3600);
var minutes = Math.floor((sec_num - (days * (3600 * 24)) - (hours * 3600)) / 60);
var seconds = Math.floor(sec_num - (days * (3600 * 24)) - (hours * 3600) - (minutes * 60));
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
return days+':'+ hours+':'+minutes+':'+seconds;
}

