Javascript返回两个日期之间的天数,小时数,分钟数,秒数

its*_*sme 49 javascript datetime

有没有人可以链接我的一些教程,我可以找到如何在2个unix日期之间的javascript中返回天,小时,分钟,秒?

我有:

var date_now = unixtimestamp;
var date_future = unixtimestamp;
Run Code Online (Sandbox Code Playgroud)

我想返回(实时)从date_now到date_future的剩余天数,小时数,分钟数.

Aln*_*tak 144

只需计算出以秒为单位的差异(不要忘记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
Run Code Online (Sandbox Code Playgroud)

EDIT代码调整,因为我刚刚意识到原始代码返回总小时数等,而不是计算整天后剩余的小时数.

  • 我要改变```var seconds = delta%60;```到```var seconds = Math.floor(delta%60);``` (5认同)

jac*_*ill 30

这里是javascript :(例如,未来的日期是新年)

演示(每秒更新)

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);
Run Code Online (Sandbox Code Playgroud)


Rie*_*u͢s 25

我把它称为"雪人卡尔☃方法",我认为当你需要额外的时间跨度,如周,飞蛾,年,几个世纪时,它会更加灵活......并且不需要太多的重复代码:

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);
Run Code Online (Sandbox Code Playgroud)

有个 FIDDLE/ ES6 Version (2018)/TypeScript Version (2019)

灵感来自Alnitak的回答.

  • 很优雅的解决方案 (3认同)
  • 请注意,此代码确实依赖于按指定顺序枚举 s 的键,这仅在 ES2015 或更高版本中保证为真。 (3认同)

Chr*_*yer 17

它在 JavaScript 中工作有一点不同的风格(也许对某些人来说更具可读性),而且它也可以在 TypeScript 中工作

如果您确保第一个日期始终大于第二个日期,则不需要 Math.abs() 模运算周围的圆括号也是不必要的。我保留它们以备清关。

let diffTime = Math.abs(new Date().valueOf() - new Date('2021-11-22T18:30:00').valueOf());
let days = diffTime / (24*60*60*1000);
let hours = (days % 1) * 24;
let minutes = (hours % 1) * 60;
let secs = (minutes % 1) * 60;
[days, hours, minutes, secs] = [Math.floor(days), Math.floor(hours), Math.floor(minutes), Math.floor(secs)]

console.log(days+'d', hours+'h', minutes+'m', secs+'s');
Run Code Online (Sandbox Code Playgroud)


Cis*_*Got 9

我的解决方案没有那么清楚,但我把它作为另一个例子

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;
}
Run Code Online (Sandbox Code Playgroud)


csg*_*csg 8

请注意,仅根据差异进行计算不会涵盖所有情况:闰年和"夏令时"的切换.

Javascript用于处理日期的内置库很差.我建议你使用第三方javascript库,例如MomentJS ; 你可以在这里看到你正在寻找的功能.


ns1*_*s16 7

使用moment.js库,例如:

var time = date_future - date_now;
var seconds = moment.duration(time).seconds();
var minutes = moment.duration(time).minutes();
var hours   = moment.duration(time).hours();
var days    = moment.duration(time).days();
Run Code Online (Sandbox Code Playgroud)


Bal*_*zar 7

因为 MomentJS 相当重且未经过优化,所以不害怕使用模块的人可能应该看看date-fns,它提供了一个intervalToDuration方法,它可以做你想要的事情:

const result = intervalToDuration({
  start: new Date(dateNow),
  end: new Date(dateFuture),
})
Run Code Online (Sandbox Code Playgroud)

这将返回一个如下所示的对象:

{
  years: 39,
  months: 2,
  days: 20,
  hours: 7,
  minutes: 5,
  seconds: 0,
}
Run Code Online (Sandbox Code Playgroud)

然后您甚至可以使用formatDuration使用您喜欢的参数将该对象显示为字符串


icl*_*126 6

简短而灵活,支持负值,尽管使用两个逗号表达式:)

\n\n
function timeUnitsBetween(startDate, endDate) {\n  let delta = Math.abs(endDate - startDate) / 1000;\n  const isNegative = startDate > endDate ? -1 : 1;\n  return [\n    [\'days\', 24 * 60 * 60],\n    [\'hours\', 60 * 60],\n    [\'minutes\', 60],\n    [\'seconds\', 1]\n  ].reduce((acc, [key, value]) => (acc[key] = Math.floor(delta / value) * isNegative, delta -= acc[key] * isNegative * value, acc), {});\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

例子:

\n\n
timeUnitsBetween(new Date("2019-02-11T02:12:03+00:00"), new Date("2019-02-11T01:00:00+00:00"));\n// { days: -0, hours: -1, minutes: -12, seconds: -3 }\n
Run Code Online (Sandbox Code Playgroud)\n\n

灵感来自RienNeVaPlu\xcd\xa2s解决方案的启发。

\n


Sce*_*tic 5

这是一个代码示例。我使用了简单的计算,而不是使用预计算,比如 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));
Run Code Online (Sandbox Code Playgroud)