【问题标题】:Jquery Date difference in Hours以小时为单位的 Jquery 日期差异
【发布时间】:2016-05-29 03:51:23
【问题描述】:

我试图在不使用任何第 3 方日期相关库的情况下以小时为单位查找 2 个日期之间的日期差异。我使用了下面的代码,但它显示了错误的时间。请有任何更好的建议或指针来纠正这个问题。

My fiddle

var FutureDate=new Date('2016-05-08T05:19:05.83');
var TodayDate = new Date();
var t1 = FutureDate.getTime();
var t2 = TodayDate.getTime();
var diffInHours = parseInt((t2-t1)/(24*3600*1000));
alert(diffInHours);

【问题讨论】:

  • 为什么你的公式中包含24?您正在尝试将毫秒转换为小时,而不是天。
  • 我想知道相差多少小时。
  • 是的。并且您在毫秒内得到了差异 (t2-t1)。那么,从数学上讲,您应该如何将毫秒转换为小时?
  • 由于额外的 24 天,您的代码会在 而不是小时内产生差异。

标签: javascript jquery date-difference


【解决方案1】:
var futureDate = new Date('2016-06-08T05:19:05.83');
var todayDate = new Date();
var milliseconds = futureDate.getTime() - todayDate.getTime();
var hours = Math.floor(milliseconds / (60 * 60 * 1000));
alert('Hours: ' + hours);
  1. 时:分 = 1:60
  2. 分:秒 = 1:60
  3. 秒:毫秒 = 1:1000
  4. 小时:毫秒 = 1:60x60x1000

【讨论】:

    【解决方案2】:

    实际上,您可以在本地相互减去日期。

    var msIn1Hour = 3600 * 1000;
    var TodayDate = new Date();
    var FutureDate = new Date('2016-05-08T05:19:05.83');
    
    alert((TodayDate - FutureDate)/msIn1Hour);
    

    注意:我不太清楚你为什么使用parseInt,因为这是用来将string 转换为int。如果要对数字进行四舍五入,请使用Math.floorMath.round

    【讨论】:

      【解决方案3】:

      只需从公式中删除除以 24 即可。那 24 实际上是将其转换为 difference in days

      t2-t1 = x milliseconds
      x/1000 = y seconds
      y/3600 = z hours
      

      当你拥有 z 时,你就完成了。所以,你不必除以 24。所以,你可以简单地写

      var FutureDate=new Date('2016-05-08T05:19:05.83');
      var TodayDate = new Date();
      var t1 = FutureDate.getTime();
      var t2 = TodayDate.getTime();
      var diffInHours = Math.floor((t2-t1)/(3600*1000)); //Removed the 24 here
      alert(diffInHours);
      

      【讨论】:

      • 根据上述评论 parseInt 可能不是最佳选择。
      猜你喜欢
      • 1970-01-01
      • 2013-09-15
      • 1970-01-01
      • 2021-10-26
      • 2016-08-12
      • 1970-01-01
      • 1970-01-01
      • 2019-02-15
      • 1970-01-01
      相关资源
      最近更新 更多