JavaScript 中日期之间的差异

发布于 2024-08-16 00:00:49 字数 21 浏览 2 评论 0原文

如何找出两个日期之间的差异?

How to find the difference between two dates?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

夏天碎花小短裙 2024-08-23 00:00:49

通过使用 Date 对象及其毫秒值,可以计算差异:

var a = new Date(); // Current date now.
var b = new Date(2010, 0, 1, 0, 0, 0, 0); // Start of 2010.
var d = (b-a); // Difference in milliseconds.

您可以得到秒数(作为整数/整数),方法是将毫秒除以 1000 将其转换为秒,然后将结果转换为整数(这会删除代表毫秒的小数部分):

var seconds = parseInt((b-a)/1000);

然后您可以获得整数分钟< /code> 将秒除以 60 并将其转换为整数,然后将小时除以 60 将分钟转换为整数,然后以同样的方式更长的时间单位。由此,可以创建一个函数来获取下一个单位的值中的时间单位的最大总量和余下的下单位:

function get_whole_values(base_value, time_fractions) {
    time_data = [base_value];
    for (i = 0; i < time_fractions.length; i++) {
        time_data.push(parseInt(time_data[i]/time_fractions[i]));
        time_data[i] = time_data[i] % time_fractions[i];
    }; return time_data;
};
// Input parameters below: base value of 72000 milliseconds, time fractions are
// 1000 (amount of milliseconds in a second) and 60 (amount of seconds in a minute). 
console.log(get_whole_values(72000, [1000, 60]));
// -> [0,12,1] # 0 whole milliseconds, 12 whole seconds, 1 whole minute.

如果您想知道上面为第二个 Date 对象 是,请参阅下面的名称:

new Date(<year>, <month>, <day>, <hours>, <minutes>, <seconds>, <milliseconds>);

正如此解决方案的注释中所述,您不一定需要提供所有这些值,除非它们对于您希望表示的日期是必需的。

By using the Date object and its milliseconds value, differences can be calculated:

var a = new Date(); // Current date now.
var b = new Date(2010, 0, 1, 0, 0, 0, 0); // Start of 2010.
var d = (b-a); // Difference in milliseconds.

You can get the number of seconds (as a integer/whole number) by dividing the milliseconds by 1000 to convert it to seconds then converting the result to an integer (this removes the fractional part representing the milliseconds):

var seconds = parseInt((b-a)/1000);

You could then get whole minutes by dividing seconds by 60 and converting it to an integer, then hours by dividing minutes by 60 and converting it to an integer, then longer time units in the same way. From this, a function to get the maximum whole amount of a time unit in the value of a lower unit and the remainder lower unit can be created:

function get_whole_values(base_value, time_fractions) {
    time_data = [base_value];
    for (i = 0; i < time_fractions.length; i++) {
        time_data.push(parseInt(time_data[i]/time_fractions[i]));
        time_data[i] = time_data[i] % time_fractions[i];
    }; return time_data;
};
// Input parameters below: base value of 72000 milliseconds, time fractions are
// 1000 (amount of milliseconds in a second) and 60 (amount of seconds in a minute). 
console.log(get_whole_values(72000, [1000, 60]));
// -> [0,12,1] # 0 whole milliseconds, 12 whole seconds, 1 whole minute.

If you're wondering what the input parameters provided above for the second Date object are, see their names below:

new Date(<year>, <month>, <day>, <hours>, <minutes>, <seconds>, <milliseconds>);

As noted in the comments of this solution, you don't necessarily need to provide all these values unless they're necessary for the date you wish to represent.

再浓的妆也掩不了殇 2024-08-23 00:00:49

我发现了这个,它对我来说效果很好:

计算两个已知日期之间的差异

不幸的是,计算两个已知日期之间的日期间隔(例如天、周或月)并不那么容易,因为您可以不仅仅是将 Date 对象添加在一起。为了在任何类型的计算中使用 Date 对象,我们必须首先检索 Date 的内部毫秒值,该值存储为一个大整数。执行此操作的函数是 Date.getTime()。转换两个日期后,用前一个日期减去后一个日期将返回以毫秒为单位的差值。然后可以通过将该数字除以相应的毫秒数来确定所需的间隔。例如,要获取给定毫秒数的天数,我们将除以一天中的毫秒数 86,400,000(1000 x 60 秒 x 60 分钟 x 24 小时):

Date.daysBetween = function( date1, date2 ) {
  //Get 1 day in milliseconds
  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 = date2_ms - date1_ms;

  // Convert back to days and return
  return Math.round(difference_ms/one_day); 
}

//Set the two dates
var y2k  = new Date(2000, 0, 1); 
var Jan1st2010 = new Date(y2k.getFullYear() + 10, y2k.getMonth(), y2k.getDate());
var today= new Date();
//displays 726
console.log( 'Days since ' 
           + Jan1st2010.toLocaleDateString() + ': ' 
           + Date.daysBetween(Jan1st2010, today));

舍入是可选的,具体取决于是否你是否想要部分日子。

参考

I have found this and it works fine for me:

Calculating the Difference between Two Known Dates

Unfortunately, calculating a date interval such as days, weeks, or months between two known dates is not as easy because you can't just add Date objects together. In order to use a Date object in any sort of calculation, we must first retrieve the Date's internal millisecond value, which is stored as a large integer. The function to do that is Date.getTime(). Once both Dates have been converted, subtracting the later one from the earlier one returns the difference in milliseconds. The desired interval can then be determined by dividing that number by the corresponding number of milliseconds. For instance, to obtain the number of days for a given number of milliseconds, we would divide by 86,400,000, the number of milliseconds in a day (1000 x 60 seconds x 60 minutes x 24 hours):

Date.daysBetween = function( date1, date2 ) {
  //Get 1 day in milliseconds
  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 = date2_ms - date1_ms;

  // Convert back to days and return
  return Math.round(difference_ms/one_day); 
}

//Set the two dates
var y2k  = new Date(2000, 0, 1); 
var Jan1st2010 = new Date(y2k.getFullYear() + 10, y2k.getMonth(), y2k.getDate());
var today= new Date();
//displays 726
console.log( 'Days since ' 
           + Jan1st2010.toLocaleDateString() + ': ' 
           + Date.daysBetween(Jan1st2010, today));

The rounding is optional, depending on whether you want partial days or not.

Reference

与风相奔跑 2024-08-23 00:00:49

如果您正在寻找以年、月和日组合表示的差异,我建议使用以下函数:

function interval(date1, date2) {
    if (date1 > date2) { // swap
        var result = interval(date2, date1);
        result.years  = -result.years;
        result.months = -result.months;
        result.days   = -result.days;
        result.hours  = -result.hours;
        return result;
    }
    result = {
        years:  date2.getYear()  - date1.getYear(),
        months: date2.getMonth() - date1.getMonth(),
        days:   date2.getDate()  - date1.getDate(),
        hours:  date2.getHours() - date1.getHours()
    };
    if (result.hours < 0) {
        result.days--;
        result.hours += 24;
    }
    if (result.days < 0) {
        result.months--;
        // days = days left in date1's month, 
        //   plus days that have passed in date2's month
        var copy1 = new Date(date1.getTime());
        copy1.setDate(32);
        result.days = 32-date1.getDate()-copy1.getDate()+date2.getDate();
    }
    if (result.months < 0) {
        result.years--;
        result.months+=12;
    }
    return result;
}

// Be aware that the month argument is zero-based (January = 0)
var date1 = new Date(2015, 4-1, 6);
var date2 = new Date(2015, 5-1, 9);

document.write(JSON.stringify(interval(date1, date2)));

这个解决方案将以我们自然会做的方式处理闰年(2 月 29 日)和月份长度差异(我认为)。

例如,2015年2月28日和2015年3月28日之间的间隔将被视为正好一个月,而不是28天。如果这两个日子都是 2016 年,那么差异仍然是 1 个月,而不是 29 天。

月份和日期完全相同但年份不同的日期始终会存在精确的年数差异。因此 2015-03-01 和 2016-03-01 之间的差异将恰好是 1 年,而不是 1 年零 1 天(因为将 365 天算作 1 年)。

If you are looking for a difference expressed as a combination of years, months, and days, I would suggest this function:

function interval(date1, date2) {
    if (date1 > date2) { // swap
        var result = interval(date2, date1);
        result.years  = -result.years;
        result.months = -result.months;
        result.days   = -result.days;
        result.hours  = -result.hours;
        return result;
    }
    result = {
        years:  date2.getYear()  - date1.getYear(),
        months: date2.getMonth() - date1.getMonth(),
        days:   date2.getDate()  - date1.getDate(),
        hours:  date2.getHours() - date1.getHours()
    };
    if (result.hours < 0) {
        result.days--;
        result.hours += 24;
    }
    if (result.days < 0) {
        result.months--;
        // days = days left in date1's month, 
        //   plus days that have passed in date2's month
        var copy1 = new Date(date1.getTime());
        copy1.setDate(32);
        result.days = 32-date1.getDate()-copy1.getDate()+date2.getDate();
    }
    if (result.months < 0) {
        result.years--;
        result.months+=12;
    }
    return result;
}

// Be aware that the month argument is zero-based (January = 0)
var date1 = new Date(2015, 4-1, 6);
var date2 = new Date(2015, 5-1, 9);

document.write(JSON.stringify(interval(date1, date2)));

This solution will treat leap years (29 February) and month length differences in a way we would naturally do (I think).

So for example, the interval between 28 February 2015 and 28 March 2015 will be considered exactly one month, not 28 days. If both those days are in 2016, the difference will still be exactly one month, not 29 days.

Dates with exactly the same month and day, but different year, will always have a difference of an exact number of years. So the difference between 2015-03-01 and 2016-03-01 will be exactly 1 year, not 1 year and 1 day (because of counting 365 days as 1 year).

开始看清了 2024-08-23 00:00:49
    // This is for first date
    first = new Date(2010, 03, 08, 15, 30, 10); // Get the first date epoch object
    document.write((first.getTime())/1000); // get the actual epoch values
    second = new Date(2012, 03, 08, 15, 30, 10); // Get the second date epoch object
    document.write((second.getTime())/1000); // get the actual epoch values
    diff= second - first ;
    one_day_epoch = 24*60*60 ;  // calculating one epoch
    if ( diff/ one_day_epoch > 365 ) // check if it is exceeding regular calendar year
    {
    alert( 'date is exceeding one year');
    }
    // This is for first date
    first = new Date(2010, 03, 08, 15, 30, 10); // Get the first date epoch object
    document.write((first.getTime())/1000); // get the actual epoch values
    second = new Date(2012, 03, 08, 15, 30, 10); // Get the second date epoch object
    document.write((second.getTime())/1000); // get the actual epoch values
    diff= second - first ;
    one_day_epoch = 24*60*60 ;  // calculating one epoch
    if ( diff/ one_day_epoch > 365 ) // check if it is exceeding regular calendar year
    {
    alert( 'date is exceeding one year');
    }
樱&纷飞 2024-08-23 00:00:49

这个答案基于另一个答案(链接在最后),是关于两个日期之间的差异。
您可以看到它是如何工作的,因为它很简单,还包括将差异分为
时间单位(我制作的函数)并转换为 UTC 以解决时区问题。

function date_units_diff(a, b, unit_amounts) {
    var split_to_whole_units = function (milliseconds, unit_amounts) {
        // unit_amounts = list/array of amounts of milliseconds in a
        // second, seconds in a minute, etc., for example "[1000, 60]".
        time_data = [milliseconds];
        for (i = 0; i < unit_amounts.length; i++) {
            time_data.push(parseInt(time_data[i] / unit_amounts[i]));
            time_data[i] = time_data[i] % unit_amounts[i];
        }; return time_data.reverse();
    }; if (unit_amounts == undefined) {
        unit_amounts = [1000, 60, 60, 24];
    };
    var utc_a = new Date(a.toUTCString());
    var utc_b = new Date(b.toUTCString());
    var diff = (utc_b - utc_a);
    return split_to_whole_units(diff, unit_amounts);
}

// Example of use:
var d = date_units_diff(new Date(2010, 0, 1, 0, 0, 0, 0), new Date()).slice(0,-2);
document.write("In difference: 0 days, 1 hours, 2 minutes.".replace(
   /0|1|2/g, function (x) {return String( d[Number(x)] );} ));

我上面的代码是如何工作的

日期/时间差异(以毫秒为单位)可以使用 Date 对象:

var a = new Date(); // Current date now.
var b = new Date(2010, 0, 1, 0, 0, 0, 0); // Start of 2010.

var utc_a = new Date(a.toUTCString());
var utc_b = new Date(b.toUTCString());
var diff = (utc_b - utc_a); // The difference as milliseconds.

然后计算出该差异的秒数,将其除以 1000 进行转换
毫秒转为秒,然后将结果改为整数(整数)即可去除
毫秒(小数的小数部分):var秒= parseInt(diff/1000)
另外,我可以使用相同的过程获得更长的时间单位,例如:
-(整数)分钟,将除以 60 并将结果更改为整数,
- 小时,将分钟除以60并将结果更改为整数。

我创建了一个函数来执行将差异分成
的过程
整个时间单位,名为 split_to_whole_units,通过此演示:

console.log(split_to_whole_units(72000, [1000, 60]));
// -> [1,12,0] # 1 (whole) minute, 12 seconds, 0 milliseconds.

此答案基于另一个

This answer, based on another one (link at end), is about the difference between two dates.
You can see how it works because it's simple, also it includes splitting the difference into
units of time (a function that I made) and converting to UTC to stop time zone problems.

function date_units_diff(a, b, unit_amounts) {
    var split_to_whole_units = function (milliseconds, unit_amounts) {
        // unit_amounts = list/array of amounts of milliseconds in a
        // second, seconds in a minute, etc., for example "[1000, 60]".
        time_data = [milliseconds];
        for (i = 0; i < unit_amounts.length; i++) {
            time_data.push(parseInt(time_data[i] / unit_amounts[i]));
            time_data[i] = time_data[i] % unit_amounts[i];
        }; return time_data.reverse();
    }; if (unit_amounts == undefined) {
        unit_amounts = [1000, 60, 60, 24];
    };
    var utc_a = new Date(a.toUTCString());
    var utc_b = new Date(b.toUTCString());
    var diff = (utc_b - utc_a);
    return split_to_whole_units(diff, unit_amounts);
}

// Example of use:
var d = date_units_diff(new Date(2010, 0, 1, 0, 0, 0, 0), new Date()).slice(0,-2);
document.write("In difference: 0 days, 1 hours, 2 minutes.".replace(
   /0|1|2/g, function (x) {return String( d[Number(x)] );} ));

How my code above works

A date/time difference, as milliseconds, can be calculated using the Date object:

var a = new Date(); // Current date now.
var b = new Date(2010, 0, 1, 0, 0, 0, 0); // Start of 2010.

var utc_a = new Date(a.toUTCString());
var utc_b = new Date(b.toUTCString());
var diff = (utc_b - utc_a); // The difference as milliseconds.

Then to work out the number of seconds in that difference, divide it by 1000 to convert
milliseconds to seconds, then change the result to an integer (whole number) to remove
the milliseconds (fraction part of that decimal): var seconds = parseInt(diff/1000).
Also, I could get longer units of time using the same process, for example:
- (whole) minutes, dividing seconds by 60 and changing the result to an integer,
- hours, dividing minutes by 60 and changing the result to an integer.

I created a function for doing that process of splitting the difference into
whole units of time, named split_to_whole_units, with this demo:

console.log(split_to_whole_units(72000, [1000, 60]));
// -> [1,12,0] # 1 (whole) minute, 12 seconds, 0 milliseconds.

This answer is based on this other one.

守望孤独 2024-08-23 00:00:49

您还可以使用它的

export function diffDateAndToString(small: Date, big: Date) {


    // To calculate the time difference of two dates 
    const Difference_In_Time = big.getTime() - small.getTime()

    // To calculate the no. of days between two dates 
    const Days = Difference_In_Time / (1000 * 3600 * 24)
    const Mins = Difference_In_Time / (60 * 1000)
    const Hours = Mins / 60

    const diffDate = new Date(Difference_In_Time)

    console.log({ date: small, now: big, diffDate, Difference_In_Days: Days, Difference_In_Mins: Mins, Difference_In_Hours: Hours })

    var result = ''

    if (Mins < 60) {
        result = Mins + 'm'
    } else if (Hours < 24) result = diffDate.getMinutes() + 'h'
    else result = Days + 'd'
    return { result, Days, Mins, Hours }
}

结果 { result: '30d', Days: 30, Mins: 43200, Hours: 720 }

You can also use it

export function diffDateAndToString(small: Date, big: Date) {


    // To calculate the time difference of two dates 
    const Difference_In_Time = big.getTime() - small.getTime()

    // To calculate the no. of days between two dates 
    const Days = Difference_In_Time / (1000 * 3600 * 24)
    const Mins = Difference_In_Time / (60 * 1000)
    const Hours = Mins / 60

    const diffDate = new Date(Difference_In_Time)

    console.log({ date: small, now: big, diffDate, Difference_In_Days: Days, Difference_In_Mins: Mins, Difference_In_Hours: Hours })

    var result = ''

    if (Mins < 60) {
        result = Mins + 'm'
    } else if (Hours < 24) result = diffDate.getMinutes() + 'h'
    else result = Days + 'd'
    return { result, Days, Mins, Hours }
}

results in { result: '30d', Days: 30, Mins: 43200, Hours: 720 }

溺渁∝ 2024-08-23 00:00:49
Date.prototype.addDays = function(days) {

   var dat = new Date(this.valueOf())
   dat.setDate(dat.getDate() + days);
   return dat;
}

function getDates(startDate, stopDate) {

  var dateArray = new Array();
  var currentDate = startDate;
  while (currentDate <= stopDate) {
    dateArray.push(currentDate);
    currentDate = currentDate.addDays(1);
  }
  return dateArray;
}

var dateArray = getDates(new Date(), (new Date().addDays(7)));

for (i = 0; i < dateArray.length; i ++ ) {
  //  alert (dateArray[i]);

    date=('0'+dateArray[i].getDate()).slice(-2);
    month=('0' +(dateArray[i].getMonth()+1)).slice(-2);
    year=dateArray[i].getFullYear();
    alert(date+"-"+month+"-"+year );
}
Date.prototype.addDays = function(days) {

   var dat = new Date(this.valueOf())
   dat.setDate(dat.getDate() + days);
   return dat;
}

function getDates(startDate, stopDate) {

  var dateArray = new Array();
  var currentDate = startDate;
  while (currentDate <= stopDate) {
    dateArray.push(currentDate);
    currentDate = currentDate.addDays(1);
  }
  return dateArray;
}

var dateArray = getDates(new Date(), (new Date().addDays(7)));

for (i = 0; i < dateArray.length; i ++ ) {
  //  alert (dateArray[i]);

    date=('0'+dateArray[i].getDate()).slice(-2);
    month=('0' +(dateArray[i].getMonth()+1)).slice(-2);
    year=dateArray[i].getFullYear();
    alert(date+"-"+month+"-"+year );
}
莳間冲淡了誓言ζ 2024-08-23 00:00:49
var DateDiff = function(type, start, end) {

    let // or var
        years = end.getFullYear() - start.getFullYear(),
        monthsStart = start.getMonth(),
        monthsEnd = end.getMonth()
    ;

    var returns = -1;

    switch(type){
        case 'm': case 'mm': case 'month': case 'months':
            returns = ( ( ( years * 12 ) - ( 12 - monthsEnd ) ) + ( 12 - monthsStart ) );
            break;
        case 'y': case 'yy': case 'year': case 'years':
            returns = years;
            break;
        case 'd': case 'dd': case 'day': case 'days':
            returns = ( ( end - start ) / ( 1000 * 60 * 60 * 24 ) );
            break;
    }

    return returns;

}

使用

var qtMonths = DateDiff('mm', new Date('2015-05-05'), new Date());

var qtYears = DateDiff('yy', new Date('2015-05-05'), new Date());

var qtDays = DateDiff('dd', new Date('2015-05-05'), new Date());

<块引用>

或者

var qtMonths = DateDiff('m', new Date('2015-05-05'), new Date()); // 米 || y || d

var qtMonths = DateDiff('月份', new Date('2015-05-05'), new Date()); // 月份 ||年||日

var qtMonths = DateDiff('月份', new Date('2015-05-05'), new Date()); // 月 ||年 ||天

...

var DateDiff = function (type, start, end) {

    let // or var
        years = end.getFullYear() - start.getFullYear(),
        monthsStart = start.getMonth(),
        monthsEnd = end.getMonth()
    ;

    if(['m', 'mm', 'month', 'months'].includes(type)/*ES6*/)
        return ( ( ( years * 12 ) - ( 12 - monthsEnd ) ) + ( 12 - monthsStart ) );
    else if(['y', 'yy', 'year', 'years'].includes(type))
        return years;
    else if (['d', 'dd', 'day', 'days'].indexOf(type) !== -1/*EARLIER JAVASCRIPT VERSIONS*/)
        return ( ( end - start ) / ( 1000 * 60 * 60 * 24 ) );
    else
        return -1;

}
var DateDiff = function(type, start, end) {

    let // or var
        years = end.getFullYear() - start.getFullYear(),
        monthsStart = start.getMonth(),
        monthsEnd = end.getMonth()
    ;

    var returns = -1;

    switch(type){
        case 'm': case 'mm': case 'month': case 'months':
            returns = ( ( ( years * 12 ) - ( 12 - monthsEnd ) ) + ( 12 - monthsStart ) );
            break;
        case 'y': case 'yy': case 'year': case 'years':
            returns = years;
            break;
        case 'd': case 'dd': case 'day': case 'days':
            returns = ( ( end - start ) / ( 1000 * 60 * 60 * 24 ) );
            break;
    }

    return returns;

}

Usage

var qtMonths = DateDiff('mm', new Date('2015-05-05'), new Date());

var qtYears = DateDiff('yy', new Date('2015-05-05'), new Date());

var qtDays = DateDiff('dd', new Date('2015-05-05'), new Date());

OR

var qtMonths = DateDiff('m', new Date('2015-05-05'), new Date()); // m || y || d

var qtMonths = DateDiff('month', new Date('2015-05-05'), new Date()); // month || year || day

var qtMonths = DateDiff('months', new Date('2015-05-05'), new Date()); // months || years || days

...

var DateDiff = function (type, start, end) {

    let // or var
        years = end.getFullYear() - start.getFullYear(),
        monthsStart = start.getMonth(),
        monthsEnd = end.getMonth()
    ;

    if(['m', 'mm', 'month', 'months'].includes(type)/*ES6*/)
        return ( ( ( years * 12 ) - ( 12 - monthsEnd ) ) + ( 12 - monthsStart ) );
    else if(['y', 'yy', 'year', 'years'].includes(type))
        return years;
    else if (['d', 'dd', 'day', 'days'].indexOf(type) !== -1/*EARLIER JAVASCRIPT VERSIONS*/)
        return ( ( end - start ) / ( 1000 * 60 * 60 * 24 ) );
    else
        return -1;

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文