如何计算两个日期之间的天数?[重复]

2020/10/06 18:01 · javascript ·  · 0评论
  1. 我正在计算从“开始”到“结束”日期之间的天数。例如,如果起始日期为2010年4月13日,起始日期为2010年5月15日,则结果应为

  2. 如何使用JavaScript获得结果?

const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const firstDate = new Date(2008, 1, 12);
const secondDate = new Date(2008, 1, 22);

const diffDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));

这是执行此操作的函数:

function days_between(date1, date2) {

    // The number of milliseconds in one day
    const ONE_DAY = 1000 * 60 * 60 * 24;

    // Calculate the difference in milliseconds
    const differenceMs = Math.abs(date1 - date2);

    // Convert back to days and return
    return Math.round(differenceMs / ONE_DAY);

}

这是我用的。如果仅减去日期,它将无法跨夏令时边界使用(例如4月1日至4月30日或10月1日至10月31日)。这会减少所有时间,以确保您有一天可以使用UTC消除DST问题。

var nDays = (    Date.UTC(EndDate.getFullYear(), EndDate.getMonth(), EndDate.getDate()) -
                 Date.UTC(StartDate.getFullYear(), StartDate.getMonth(), StartDate.getDate())) / 86400000;

作为功​​能:

function DaysBetween(StartDate, EndDate) {
  // The number of milliseconds in all UTC days (no DST)
  const oneDay = 1000 * 60 * 60 * 24;

  // A day in UTC always lasts 24 hours (unlike in other time formats)
  const start = Date.UTC(EndDate.getFullYear(), EndDate.getMonth(), EndDate.getDate());
  const end = Date.UTC(StartDate.getFullYear(), StartDate.getMonth(), StartDate.getDate());

  // so it's safe to divide by 24 hours
  return (start - end) / oneDay;
}

这是我的实现:

function daysBetween(one, another) {
  return Math.round(Math.abs((+one) - (+another))/8.64e7);
}

+<date>将类型强制转换为整数表示形式,并且具有与相同的效果,<date>.getTime()并且8.64e7是一天中的毫秒数。

调整以适应夏令时差异。尝试这个:

  function daysBetween(date1, date2) {

 // adjust diff for for daylight savings
 var hoursToAdjust = Math.abs(date1.getTimezoneOffset() /60) - Math.abs(date2.getTimezoneOffset() /60);
 // apply the tz offset
 date2.addHours(hoursToAdjust); 

    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()

    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms)

    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY)

}

// you'll want this addHours function too 

Date.prototype.addHours= function(h){
    this.setHours(this.getHours()+h);
    return this;
}

我为另一位询问该帖子的人写了这个解决方案,他问如何计算两个日期之间的差,所以我分享我准备的内容:

// Here are the two dates to compare
var date1 = '2011-12-24';
var date2 = '2012-01-01';

// First we split the values to arrays date1[0] is the year, [1] the month and [2] the day
date1 = date1.split('-');
date2 = date2.split('-');

// Now we convert the array to a Date object, which has several helpful methods
date1 = new Date(date1[0], date1[1], date1[2]);
date2 = new Date(date2[0], date2[1], date2[2]);

// We use the getTime() method and get the unixtime (in milliseconds, but we want seconds, therefore we divide it through 1000)
date1_unixtime = parseInt(date1.getTime() / 1000);
date2_unixtime = parseInt(date2.getTime() / 1000);

// This is the calculated difference in seconds
var timeDifference = date2_unixtime - date1_unixtime;

// in Hours
var timeDifferenceInHours = timeDifference / 60 / 60;

// and finaly, in days :)
var timeDifferenceInDays = timeDifferenceInHours  / 24;

alert(timeDifferenceInDays);

您已经跳过了代码中的某些步骤,我已经编写了它,以使其易于理解。

您将在此处找到一个运行中的示例:http : //jsfiddle.net/matKX/

从我的小日期差计算器:

var startDate = new Date(2000, 1-1, 1);  // 2000-01-01
var endDate =   new Date();              // Today

// Calculate the difference of two dates in total days
function diffDays(d1, d2)
{
  var ndays;
  var tv1 = d1.valueOf();  // msec since 1970
  var tv2 = d2.valueOf();

  ndays = (tv2 - tv1) / 1000 / 86400;
  ndays = Math.round(ndays - 0.5);
  return ndays;
}

所以你会打电话给:

var nDays = diffDays(startDate, endDate);

(完整资源位于http://david.tribble.com/src/javascript/jstimespan.html。)

附录

可以通过更改以下行来改进代码:

  var tv1 = d1.getTime();  // msec since 1970
  var tv2 = d2.getTime();
本文地址:http://javascript.askforanswer.com/ruhejisuanlianggeriqizhijiandetianshuzhongfu.html
文章标签: ,   ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!