【问题标题】:Get the next upcoming Friday at 5 PM在下午 5 点获取下一个即将到来的星期五
【发布时间】:2018-01-31 22:37:40
【问题描述】:

我需要显示距离截止日期还有多远,即每周五下午 5 点。 Moment 将为我提供一周中某一天的日期,但它始终是当前时间,因此截止日期始终显示“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`;
}
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.js"&gt;&lt;/script&gt;

【问题讨论】:

    标签: momentjs


    【解决方案1】:

    您必须将时间(17:00)设置为deadline,而不是获取当前时间,您可以使用时刻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`;
    }
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.js"&gt;&lt;/script&gt;

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-21
      • 2021-12-04
      • 2012-10-05
      • 2018-09-17
      • 1970-01-01
      • 1970-01-01
      • 2015-11-22
      • 2021-02-17
      相关资源
      最近更新 更多