JavaScript - 获取两个日期之间的分钟数

2022-08-30 00:57:57

如果我有两个日期,我如何使用JavaScript在几分钟内获得两个日期之间的差异?


答案 1

您可以签出此代码:

var today = new Date();
var Christmas = new Date(today.getFullYear() + "-12-25");
var diffMs = (Christmas - today); // milliseconds between now & Christmas
var diffDays = Math.floor(diffMs / 86400000); // days
var diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
console.log(diffDays + " days, " + diffHrs + " hours, " + diffMins + " minutes until Christmas =)");

或者,如果您不想对分钟数进行舍入,则丢弃秒数。var diffMins = Math.floor((...


答案 2

减去两个对象可以得出毫秒的差异,例如:Date

var diff = Math.abs(new Date('2011/10/09 12:00') - new Date('2011/10/09 00:00'));

Math.abs用于能够使用绝对差值(因此给出相同的结果)。new Date('2011/10/09 00:00') - new Date('2011/10/09 12:00')

将结果除以 1000 会得到秒数。将其除以60得到分钟数。要四舍五入到整分钟,请使用或:Math.floorMath.ceil

var minutes = Math.floor((diff/1000)/60);

在此示例中,结果将为 720。

[编辑2022]添加了一个更完整的演示片段,使用上述知识。

另请参见

untilXMas();

function difference2Parts(milliseconds) {
  const secs = Math.floor(Math.abs(milliseconds) / 1000);
  const mins = Math.floor(secs / 60);
  const hours = Math.floor(mins / 60);
  const days = Math.floor(hours / 24);
  const millisecs = Math.floor(Math.abs(milliseconds)) % 1000;
  const multiple = (term, n) => n !== 1 ? `${n} ${term}s` : `1 ${term}`;

  return {
    days: days,
    hours: hours % 24,
    hoursTotal: hours,
    minutesTotal: mins,
    minutes: mins % 60,
    seconds: secs % 60,
    secondsTotal: secs,
    milliSeconds: millisecs,
    get diffStr() {
      return `${multiple(`day`, this.days)}, ${
        multiple(`hour`, this.hours)}, ${
        multiple(`minute`, this.minutes)} and ${
        multiple(`second`, this.seconds)}`;
    },
    get diffStrMs() {
      return `${this.diffStr.replace(` and`, `, `)} and ${
        multiple(`millisecond`, this.milliSeconds)}`;
    },
  };
}

function untilXMas() {
  const nextChristmas = new Date(Date.UTC(new Date().getFullYear(), 11, 25));
  const report = document.querySelector(`#nextXMas`);
  const diff = () => {
    const diffs = difference2Parts(nextChristmas - new Date());
    report.innerHTML = `Awaiting next XMas