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

新手上路,请多包涵

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

原文由 John 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

您可以签出此代码:

 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((... 如果您不想舍入分钟,则丢弃秒。

原文由 Darin Dimitrov 发布,翻译遵循 CC BY-SA 4.0 许可协议

减去两个 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。

[ edit 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 🙂 (${
      diffs.diffStrMs.replace(/(\d+)/g, a => `<b>${a}</b>`)})<br>
      <br>In other words, until next XMas lasts&hellip;<br>
      In minutes: <b>${diffs.minutesTotal}</b><br>In hours: <b>${
      diffs.hoursTotal}</b><br>In seconds: <b>${diffs.secondsTotal}</b>`;
    setTimeout(diff, 200);
  };
  return diff();
}
 body {
  font: 14px/17px normal verdana, arial;
  margin: 1rem;
}
 <div id="nextXMas"></div>

原文由 KooiInc 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题