65.9K
CodeProject 正在变化。 阅读更多。
Home

如何使用 JavaScript 计算两个日期之间的差值

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.68/5 (12投票s)

2007年4月8日

viewsIcon

146276

此代码将为您提供两个日期之间的天数差。有时程序需要获得两个日期之间的差值。这是一个非常小巧且高效的代码。

引言

此代码将为您提供两个日期之间的天数差。有时程序需要获得两个日期之间的差值。这是一个非常小巧且高效的代码。

背景

(可选) 是否有任何关于本文的背景信息可能有用,例如对所介绍的基本思想的介绍?

使用代码

如何使用文章或代码的简要说明。类名、方法和属性,以及任何技巧或提示。

代码块应设置为“Formatted”样式,如下所示

//
// Any source code blocks look like this
//
        t1="10/10/2006" ;

        t2="15/10/2006";

 
   //Total time for one day
        var one_day=1000*60*60*24; 
//Here we need to split the inputed dates to convert them into standard format
for furter execution
        var x=t1.split("/");     
        var y=t2.split("/");
  //date format(Fullyear,month,date) 

        var date1=new Date(x[2],(x[1]-1),x[0]);
  
        var date2=new Date(y[2],(y[1]-1),y[0])
        var month1=x[1]-1;
        var month2=y[1]-1;
        
        //Calculate difference between the two dates, and convert to days
               
        _Diff=Math.ceil((date2.getTime()-date1.getTime())/(one_day)); 
//_Diff gives the diffrence between the two dates.

请记得使用语言下拉菜单设置代码片段的语言。

使用“var”按钮将变量或类名包装在 <code> 标签中,例如 this

关注点

在编写代码的过程中,你学到了什么有趣/好玩/令人恼火的东西吗? 你做了什么特别巧妙、疯狂或异想天开的事情吗?

历史

在此处保持您所做的任何更改或改进的实时更新。

© . All rights reserved.