代码之家  ›  专栏  ›  技术社区  ›  Paul

使用moment.js计算到下一次出现2pm的时间。

  •  3
  • Paul  · 技术社区  · 6 年前

    我想用moment.js计算下一次下午2点之前的剩余时间。

    到目前为止,根据我发现的另一个脚本,我有以下内容:

    var getTimeLeft = function(){
      var now = moment();
      var deadline = now.clone().hour(14).minute(0).second(0);
      if(now.isAfter(deadline)) {
        var tomorrow  = moment(new Date()).add(1,'days').hour(14).minute(0).second(0);
        console.log(tomorrow.from(now));
      }else {
        console.log(deadline.from(now));
      }
    }
    getTimeLeft();
    

    如果时间在下午2点之前,则返回四舍五入格式的时间,即“5小时”

    如果时间超过下午2点,则返回“一天内”

    我如何编辑这个脚本,以便在下午2点之前运行,我可以得到格式的答案 "4hrs 57mins" 如果不是四舍五入,如果是第二天,它也会做同样的事情。 "21hrs 2mins" ?

    干杯

    1 回复  |  直到 6 年前
        1
  •  1
  •   Jason Aller    6 年前

    事实上 moment.from() method 始终返回 string 在这种格式中,您无法获得 hours minutes 或作为 milliseconds .

    解决方案:

    显示自定义消息的一个小技巧 小时 分钟 是使用 moment.diff() method ,返回 毫秒 , seconds , 分钟 , 小时 days .

    tomorrow.diff(now, "hours") + ' hrs, ' + (tomorrow.diff(now, "minutes") % 60) + ' mins'
    

    你只需要说明 小时 / 分钟 作为 .diff() 方法获取所需格式的结果。

    演示:

    这是一个工作演示:

    var getTimeLeft = function() {
      var now = moment();
      var deadline = now.clone().hour(14).minute(0).second(0);
      if (now.isAfter(deadline)) {
        var tomorrow = moment(new Date()).add(1, 'days').hour(14).minute(0).second(0);
        console.log(tomorrow.diff(now, "hours") + ' hrs, ' + (tomorrow.diff(now, "minutes") % 60) + ' mins');
      } else {
        console.log(deadline.diff(now, "hours") + ' hrs, ' + (deadline.diff(now, "minutes") % 60) + ' mins');
      }
    }
    getTimeLeft();
    <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.7.0/moment.js"></script>

    注:

    当然,当只有 小时 或仅 分钟 作为差异。