2个日期-有什么区别?

A common challenge, or question, when working with two calendar dates is:

使用两个日历日期时,常见的挑战或问题是:

What is the difference between the specified days?

As is frequently the case, the answer is: It depends...

通常,答案是:这取决于...

What kind of difference do you want?

Given two date objects, you can simply subtract one from the other to get a difference.

给定两个日期对象,您可以简单地从另一个中减去一个以获得差值。

  var day1 = new Date( '2/29/2000 23:59:58' );
  var day2 = new Date( 'Feb 27, 2009 00:00:00' );
  alert( day2 - day1 )

This causes us to ask: What does the displayed value (283824002000) represent?

这使我们问:

It's the number of milliseconds between the specified dates & times.

它是指定日期和时间之间的毫秒数。

Is there an easy way to convert this into something useable?

Sure.  This works reasonably well:

当然。 这相当有效:

Technique #1

技术#1

  var day1 = new Date( '2/29/2000 23:59:58' );
  var day2 = new Date( 'Feb 27, 2009 00:00:00' );
  var units = 'Years,Days,Hours,Minutes,Seconds'.split( ',' );
  var vals = [ 365 * 24 * 60 * 60, 24 * 60 * 60, 60 * 60, 60 ];
  var msg  = '';
  var secs = Math.abs( Math.floor( ( day2 - day1 ) / 1000 ) );
  for ( var i = 0; i < vals.length; i++ ) {
    var result = Math.floor( secs / vals[ i ] );
    if ( result ) {
      msg += '\n' + units[ i ] + ' ' + result;
    }
    secs -= result * vals[ i ];
  }
  if ( secs ) {
    msg += '\n' + units[ i ] + ' ' + secs;
  }
  alert( msg.substr( 1 ) );

Wait a minute... (pun intended) This does provide an accurate difference, but it really isn't the kind of value that people expect.  If you use this code to display the difference between 1/28/2009 and 2/28/2009, the result is "31 days".  Although accurate, this is not always pleasing to people, who might be expecting something like "1 month".

请稍等...(这是双关语的意思),它确实提供了准确的区别,但实际上并不是人们期望的那种价值。 如果使用此代码显示2009年1月28日和2009年2月28日之间的差额,则结果为“ 31天”。 尽管准确,但这并不总是让人感到满意,他们可能期望“ 1个月”之类的东西。

Can we expand this simple loop to include the calculation of the difference in months? Well, the answer to that question is "not without a bit more work".   Why not? Because the length of each month is not a fixed value, that's why. So, how do we compute a difference between two dates that takes months into consideration? Conceptually, this is pretty straight-forward:

+Compute the difference for each of the following parts of the two dates:

+计算两个日期以下各部分的差额:

  - Years

-年

  - Months

-月

  - Days

- 天

  - Hours

- 小时

  - Minutes

- 分钟

  - Seconds

-秒

+Then, check these differences (bottom to top), looking for negative values. When you find a negative value:

+然后,检查这些差异(从下到上),寻找负值。 当您发现负值时:

- decrement the next larger units

-减少下一个更大的单位

- add "the appropriate amount" to the current value.

-将“适当的数量”添加到当前值。

The biggest question is: What is the "appropriate value" for the number of days in a month?

最大的问题是:

Again the answer is: it depends...

答案再次是:这取决于...

How do we compute the "appropriate" number of days for the month?

Again, we can make use of a really nice property of the JavaScript date object.  That is, if you construct a Date object with the "day of the month" as 0, the result will be the last day of the preceding month.  For example, to create a new Date object to display the last day in February of 2009, you could simply:

同样,我们可以利用JavaScript日期对象的一个​​非常好的属性。 也就是说,如果构造“日期”为0的Date对象,则结果将是前一个月的最后一天。 例如,要创建一个新的Date对象以显示2009年2月的最后一天,您可以简单地:

alert( new Date( 2009, 2, 0 ) );

Note: the parameters for the date constructor are:

注意:日期构造函数的参数为​​:

- The full (4 digit) year

-完整的(4位)年份

- The ordinal month number (where Jan = 0, Feb = 1, ... and Dec = 11)

-序号月份(其中Jan = 0,Feb = 1,...和Dec = 11)

- The date of the month

-月份的日期

So, the date value being constructed is for the 0th day of the 3rd month (March), which is interpreted as the last day of the 2nd month (February), and the result will be a date object for: Sat Feb 28, 2009

因此,正在构造的日期值为第三个月的第三天(三月),这被解释为第二个月的最后一天(二月),其结果将是以下日期对象:2009年2月28日,星期六

So, how do we use this in our script?

Technique #2

技术2

var day1 = new Date( 'Dec 29, 1977 23:59:58' );
var day2 = new Date( 'Mar 2, 2009 12:00:00' );
var diff = [
             day2.getFullYear() - day1.getFullYear(),
             day2.getMonth()    - day1.getMonth(),
             day2.getDate()     - day1.getDate(),
             day2.getHours()    - day1.getHours(),
             day2.getMinutes()  - day1.getMinutes(),
             day2.getSeconds()  - day1.getSeconds()
           ];
var delta = [ 12, 31, 24, 60, 60 ];
delta[ 1 ] = ( new Date( day2.getFullYear(), day2.getMonth(), 0 ) ).getDate();

for ( var i = diff.length - 1; i > -1; i-- ) {
  if ( diff[ i ] < 0 ) {
    if ( i > -1 ) {
      var j = i - 1;
      diff[ i ] += delta[ j ];
      diff[ j ]--;
    } else {
      alert( 'Negative year difference: ' + diff[ 0 ] );
    }
  }
}

Before adjusting the values, the original contents of the 'diff' array were [ 32,-9,-27,-11,-59,-58 ].

在调整值之前,“ diff”数组的原始内容为[32,-9,-27,-11,-59,-58]。

After adjusting the values, we have [ 31,2,0,12,0,2 ] (i.e., 31 years, 2 months, 12 hours, and 2 seconds).

调整值后,我们有[31,2,0,12,0,2](即31年,2个月,12小时和2秒)。

This looks reasonable, but if we compare the output of the two techniques, we find that the result of the first technique shows that the difference between "Dec 29, 1977 23:59:58" and "Mar 2, 2009 12:00:00" is:

这看起来很合理,但是如果比较这两种技术的输出,我们发现第一种技术的结果表明“ 1977年12月29日23:59:58”与“ 2009年3月2日12:00”之间的差异: 00”是:

Difference = 31 Years 70 Days 12 Hours 2 Seconds

So technique #1 has 70 days, and technique #2 has 2 months.  Wait a minute.  The longest month of the year has 31 days.  So two months has to be less than 63 days.  Why is there a difference between these two techniques?

因此,技术1有70天,技术2有2个月。 等一下。 一年中最长的一个月有31天。 因此,两个月必须少于63天。

Take a look at the difference in years.  Over a 31 year span, how many leap years do you think there are?  That's where the difference exists.  How do we determine the number of leap days that exist between two dates?

看看几年之间的差异。 在31年的时间里,您认为有多少个leap年? 那就是存在差异的地方。

First, we need an easy way to determine whether or not a specific year is a leap year.  We could use one of the readily available expressions, or we could let the JavaScript date object do it for us.  For example:

首先,我们需要一种简单的方法来确定特定年份是否为a年。 我们可以使用一种易于使用的表达式,也可以让JavaScript date对象为我们完成此操作。 例如:

function isLeapYear( y ) {
  return ( new Date( y, 1, 29 ).getDate() == 29 );
}

This simply tries to create a date object for Feb 29 of a specified year.  If the result isn't on the 29th, then it isn't a leap year, and the function returns false.

这只是尝试为指定年份的2月29日创建日期对象。 如果结果不是29日,则不是a年,该函数返回false。

So, to determine the number of leap days between two particular days, we need something like this, which handles the starting and ending dates differently.

因此,要确定两个特定日期之间的of日数,我们需要像这样的东西,它以不同的方式处理开始和结束日期。

Computing the number of Leap Days

计算Le日数

var leapdays = 0;
if ( ( day1.getMonth() < 2 ) && ( day1.getDate() < 29 ) )  {
  if ( isLeapYear( day1.getFullYear() ) ) {
    leapdays++;
  }
}
for ( var year = day1.getFullYear() + 1; year < day2.getFullYear(); year++  ) {
  if ( isLeapYear( year ) ) {
    leapdays++;
  }
}
if ( isLeapYear( day2.getFullYear() ) && ( ( day2.getMonth() > 1 ) || ( ( day2.getMonth() == 1 ) && ( day2.getDate() > 28 ) ) ) ) {
  leapdays++;
}

So adding the above to the calculations found in technique #2, we find that 8 leap days exist between the two dates.  So, the total difference, as calculated by technique #2 is:

因此,将以上内容添加到方法2中的计算中,我们发现两个日期之间存在8个leap日。 因此,通过技术#2计算得出的总差异为:

Years: 31
Months: 2
Days : 0
Hours: 12
Minutes: 0
Seconds :  2
Leap Days: 8

Sample pages are available below.

示例页面如下。

Technique-1.html.txt Technique-1.html.txt Technique-2.html.txt Technique-2.html.txt Technique-2b.html.txt Technique-2b.html.txt

Hopefully you find this article, and these samples helpful...  

希望您能找到这篇文章,并且这些示例对您有所帮助...

翻译自: https://www.experts-exchange.com/articles/483/2-Dates-What's-the-difference.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值