【问题标题】:jquery date object difference in 2 date2日期中的jquery日期对象差异
【发布时间】:2013-08-20 16:27:22
【问题描述】:

我一直在编写此脚本以获取两个日期之间的差异。但是时间会弄乱脚本(http://jsfiddle.net/HuGvd/)。

当脚本在同一天进入新月份时,脚本将停止正常工作。我也尝试在这个脚本中添加分钟,但没有运气真的需要这个家伙的帮助。

function getDateDiff(timestamp) {
if (null === timestamp || timestamp === "" || timestamp === "undefined") return "?";
var splitDate = ((timestamp.toString().split('T'))[0]).split('-');
var splitTime = ((timestamp.toString().split('T'))[1]).split(':');
var d1 = new Date();
var d1Y = d1.getFullYear();
var d2Y = parseInt(splitDate[0], 10);
var d1M = d1.getMonth() + 1;
var d2M = parseInt(splitDate[1], 10);
var d1D = d1.getDate();
var d2D = parseInt(splitDate[2], 10);
var d1H = d1.getHours();
var d2H = parseInt(splitTime[0], 10);
var diffInHours = (d1H + 24 * d1D + 30) - (d2H + 24 * d2D + 30);
if (diffInHours < 24) return diffInHours + " hour";
var diffInDays = (d1D + 30 * d1M + 12) - (d2D + 30 * d2M + 12);
if (diffInDays < 7) return diffInDays + " days";
else if (diffInDays >= 7 && diffInDays < 14) return "1 week";
else if (diffInDays >= 14 && diffInDays < 30) return Math.floor(diffInDays / 7) + " weeks";
var diffInMonths = (d1M + 12 * d1Y) - (d2M + 12 * d2Y);
if (diffInMonths <= 1) return "1 month";
else if (diffInMonths < 12) return diffInMonths + " months";
var diffInYears = Math.floor(diffInMonths / 12);
if (diffInYears <= 1) return "1 year";
else if (diffInYears < 12) return diffInYears + " years";
}

【问题讨论】:

    标签: javascript jquery function datediff


    【解决方案1】:

    日期/时间功能极其复杂,边缘情况比您可能涵盖的要多...不要推出自己的解决方案,使用内置功能。您可以像这样在 javascript 中找到两个日期之间的毫秒数:

    var now = new Date();
    var then = new Date(timestamp);
    
    var diffMS = now - then;    
    

    从那里开始,根据您想要的显示方式转换为您想要的任何单位并不难。

    http://jsfiddle.net/AMDXq/

    附带说明,这是一个相当普遍的问题。我没看过,但我确定有一个插件或库可以解决这个问题。

    【讨论】:

    • 我如何能够显示输出格式,例如 1-59 分钟 1-23 小时 1-6 天 1-4 周 1-11 个月,然后是几年,我变得如此困惑我一直在做编码的原因
    • 每次转换为更大的单位时,请检查值并查看是否要显示该单位或再次转换。一种简单的方法是查看您是否拥有多个下一个单元。
    • “日期/时间功能极其复杂,边缘情况比你可能覆盖的要多”。我完全不同意,如果您知道自己想要什么,那就很简单了。
    • RobG 的解决方案是什么?这对我来说很难,因为我是 javascript 新手
    • @RobG BS。在不使用Date() 对象的情况下,向我展示您的代码以查找“2012-08-09T22:15:03.22”和“2013-08-13T12:10:03.22”之间的毫秒数。
    【解决方案2】:

    这里是查找两个日期之间差异的解决方案。策略是将字符串转换为日期对象,然后计算差值并返回年、月、日等值的数组。

    我为“精确”添加了一个参数,因此默认情况下它会返回一个整天的值(例如 2013-08-13T23:59:59Z 到 2013-08-14T00:00:01Z 是一天)或精确(上述差异为 2 秒)。

    // Expects start date to be before end date
    // Default is to deal in whole days. For precise differences 
    // (hours, minutes and seconds), set precise to true
    function dateDifference(start, end, precise) {
      var timeDiff, years, months, days, hours, minutes, seconds;
    
      // Copy date objects so don't modify originals
      var s = new Date(+start);
      var e = new Date(+end);
    console.log(s, e);
      // If not precise, set h,m,s to zero
      if (!precise) {
        s.setUTCHours(0,0,0,0);
        e.setUTCHours(0,0,0,0);
    console.log(s, e);
      }
    
      // Get estimate of year difference
      years = e.getUTCFullYear() - s.getUTCFullYear();
    
      // Add difference to start, if greater than end, remove one year
      // Note start from restored start date as adding and subtracting years
      // may not be symetric
      s.setFullYear(s.getUTCFullYear() + years);
      if (s > e) {
        --years;
        s = new Date(+start);
        s.setFullYear(s.getUTCFullYear() + years);
      }
      // Get estimate of months
      months = e.getUTCMonth() - s.getUTCMonth();
      months += months < 0? 12 : 0;
    
      // Add difference to start, adjust if greater
      s.setUTCMonth(s.getUTCMonth() + months);
      if (s > e) {
        --months;
        s = new Date(+start);
        s.setUTCFullYear(s.getUTCFullYear() + years);
        s.setUTCMonth(s.getUTCMonth() + months);
      }
    
      // Get remaining time difference
      timeDiff = e - s;
      days     =  timeDiff / 8.64e7 | 0;
      hours    = (timeDiff % 8.64e7) / 3.6e6 | 0;
      minutes  = (timeDiff % 3.6e6) / 6e4 | 0;
      seconds  = ((timeDiff % 6e4) / 1e3).toFixed(3);
    console.log(years, months, days, hours, minutes, seconds);  
      return [years, months, days, hours, minutes, seconds];
    }
    
    // Simple caluculation of days between two ES5 date objects
    function daysDifference(start,end) {
        return ((end - start) / 8.64e7).toFixed(2);
    }
    
    // Expects input in ISO8601 format: yyyy-mm-ddThh:mm:ss.sssZ
    function dateFromString(s) {
      s = s.split(/\D/);
      s[6] = s[6]? ('0.'+ s[6]) * 1000 : 0;
      return new Date(Date.UTC(s[0],--s[1],s[2],s[3],s[4],s[5],s[6]));
    }
    
    function getDateDiff(start, end, precise) {
      var d = dateDifference(dateFromString(start), dateFromString(end), precise);
      return d[0] + ' years, ' + d[1] + ' months, ' + d[2] + ' days' + 
             (precise? ', ' + d[3] + ' hours, ' + d[4] + ' minutes and ' + d[5] + ' seconds' : '') ;
    }
    
    function getDaysDiff(start, end) {
      var d = daysDifference(dateFromString(start), dateFromString(end));
      return d + ' days';
    }
    
    </script>
    
    <!-- Some HTML to show how to use it -->
    <form onsubmit="this.doCalc.onclick(); return false;">
      <label for="startDate">Start date (yyyy-mm-dd)<input name="startDate" id="startDate"
       value="2012-08-09T22:15:03.22" size="25"></label>
      <br>
      <label for="endDate">End date (yyyy-mm-dd)<input name="endDate" id="endDate"
       value="2013-08-13T12:10:03.22" size="25"></label>
      <br>
      <label for="dateDifference">Date difference: <input name="dateDifference" readonly size="100"></label>
      <br>
      <label for="daysDifference">Days difference: <input name="daysDifference" readonly size="100"></label>
      <br>
      <label for="precise"><input type="checkbox" value="precise" name="precise" id="precise">Precise?</label>
      <br>
      <input type="button" value="Calculate…" name="doCalc" onclick="
        this.form.dateDifference.value = getDateDiff(this.form.startDate.value, this.form.endDate.value, 
    
    this.form.precise.checked);
        this.form.daysDifference.value = getDaysDiff(this.form.startDate.value, this.form.endDate.value);
      ">
      <input type="reset">
    </form>
    

    【讨论】:

      猜你喜欢
      • 2017-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-14
      • 2015-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多