首页 > 解决方案 > javascript - 获取一周中第二天的日期?

问题描述

例如,如何获取下周一的日期和下午 5:30 的时间,并计算当前日期和时间与该日期和时间之间的差异?

如果我现在在 2020 年 8 月 28 日 17:35 运行它,它应该给我 2020 年 8 月 31 日 17:30 和 2 天 23 小时 55 分钟的差异。

标签: javascript

解决方案


这是工作示例:

function nextWeekMonday(date)
  {
    var diff = date.getDate() - date.getDay() + (date.getDay() === 0 ? -6 : 1);
    var currWeekMonday = new Date(date.setDate(diff)); 
    return new Date(currWeekMonday.getTime() + 7 * 24 * 60 * 60 * 1000);
  }
 
 function getDateDifference(current, future) {
  // get total seconds between the times
  var delta = Math.abs(future - current) / 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;
  
  return `${days} Days, ${hours} Hours, ${minutes} Minutes, ${seconds} Seconds`;
 }

var curr = new Date; // get current date
var nextMonday = nextWeekMonday(curr);

console.log(getDateDifference(curr, nextMonday));


推荐阅读