即将到来的下周五下午5点

时间:2018-01-31 22:37:40

标签: momentjs

我需要显示每个星期五下午5点的截止日期。片刻会给我一周中某一天的日期,但它始终是当前时间,所以截止日期总是显示“x天”,“23小时”,“59分钟”。我如何得到这一天,从特定时间开始?在我的例子中,我需要截止日期为下周五,17:00'而不是下周五,在当前时间'



console.log(timeLeft());

function timeLeft() {
  var dayINeed = 5; // for Friday

  var deadline;

  // if we haven't yet passed the day of the week that I need:
  if (moment().isoWeekday() <= dayINeed) {
    // then just give me this week's instance of that day
    deadline = moment().isoWeekday(dayINeed);
  } else {
    // otherwise, give me next week's instance of that day
    deadline = moment().add(1, 'weeks').isoWeekday(dayINeed);
  }
  console.log(deadline);
  const now = moment();
  const days = deadline.diff(now, 'days');
  const hours = deadline.subtract(days, 'days').diff(now, 'hours');
  const minutes = deadline.subtract(hours, 'hours').diff(now, 'minutes');
  return `${days} days, ${hours} hours, and ${minutes} minutes`;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.js"></script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您必须设置为deadline时间(17:00),而不是获取当前时间,您可以使用startOf()set(),只需将以下内容添加到您的代码中:

deadline.startOf('day').set({h: 17});

这样您就可以将17:00:00设置为deadline,您将获得所需的输出。

这里有一个完整的例子:

console.log(timeLeft());

function timeLeft() {
  var dayINeed = 5; // for Friday

  var deadline;

  // if we haven't yet passed the day of the week that I need:
  if (moment().isoWeekday() <= dayINeed) {
    // then just give me this week's instance of that day
    deadline = moment().isoWeekday(dayINeed);
  } else {
    // otherwise, give me next week's instance of that day
    deadline = moment().add(1, 'weeks').isoWeekday(dayINeed);
  }
  deadline.startOf('day').set({h: 17});
  console.log(deadline.format());
  const now = moment();
  const days = deadline.diff(now, 'days');
  const hours = deadline.subtract(days, 'days').diff(now, 'hours');
  const minutes = deadline.subtract(hours, 'hours').diff(now, 'minutes');
  return `${days} days, ${hours} hours, and ${minutes} minutes`;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.js"></script>

如果需要,您可以使用hour()minute()等设置工具将17:00:00设置为deadline