开发者

JavaScript - Get minutes between two dates

If I have two dates, how can I use JavaSc开发者_StackOverflow社区ript to get the difference between the two dates in minutes?


You may checkout this code:

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 =)");

or var diffMins = Math.floor((... to discard seconds if you don't want to round minutes.


Subtracting two Date objects gives you the difference in milliseconds, e.g.:

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

Math.abs is used to be able to use the absolute difference (so new Date('2011/10/09 00:00') - new Date('2011/10/09 12:00') gives the same result).

Dividing the result by 1000 gives you the number of seconds. Dividing that by 60 gives you the number of minutes. To round to whole minutes, use Math.floor or Math.ceil:

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

In this example the result will be 720.

[edit 2022] Added a more complete demo snippet, using the aforementioned knowledge.

See also

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 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜