JavaScript計算兩個日期間的天數

來源:互聯網
上載者:User

有些時候我們需要計算兩個日期間的天數,或者小時數等等。下面用JavaScript實現這個需求,然後學習一下需要用到的一些JavaScript函數。

JavaScript程式如下:

    <script type="text/javascript">  var getOffDays = function(startDate, endDate) {   //得到時間戳記相減 得到以毫秒為單位的差   var mmSec = (endDate.getTime() - startDate.getTime()); //單位轉換為天並返回  return (mmSec / 3600000 / 24);  };   alert(getOffDays(new Date(2009,8,7), new Date(2010,9,17)));   </script>
JavaScript getTime()方法

getTime()方法所返回了從1970年1月1號以來所積累的毫秒總數。用法dateObject.getTime(),這個方法得結合Date對象使用。

下面的程式得到了從1970年1月1號以來所積累的毫秒總數並輸出它:

    <script type="text/javascript">var d = new Date()document.write(d.getTime() + " milliseconds since 1970/01/01")</script>

程式運行結果為:

1284655348088 milliseconds since 1970/01/01

下面的程式我們得到了從1970年1月1號以來所用掉的年數總數並輸出它:

<script type="text/javascript">var minutes = 1000*60var hours = minutes*60var days = hours*24var years = days*365var d = new Date()var t = d.getTime()var y = t/yearsdocument.write("It's been: " + y + " years since 1970/01/01!")</script>

程式運行結果為:

It's been: 40.73615794193937 years since 1970/01/01!
JavaScript Date(日期)對象

Date 對象用於處理日期和時間。可以通過 new 關鍵詞來定義 Date 對象。以下代碼定義了名為 myDate 的 Date 對象:

var myDate = new Date();

Date 對象自動使用當前的日期和時間作為其初始值。

通過使用針對日期對象的方法,我們可以很容易地對日期進行操作。在下面的例子中,我們為日期對象設定了一個特定的日期 (2008 年 8 月 9 日):

var myDate = new Date();myDate.setFullYear(2008,7,9);

表示月份的參數介於 0 到 11 之間。也就是說,如果希望把月設定為 8 月,則參數應該是 7。

在下面的例子中,我們將日期對象設定為 5 天后的日期:

var myDate = new Date();myDate.setDate(myDate.getDate()+5);

如果增加天數會改變月份或者年份,那麼日期對象會自動完成這種轉換。

日期對象也可用於比較兩個日期。下面的代碼將當前日期與 2008 年 8 月 9 日做了比較:

var myDate=new Date();myDate.setFullYear(2008,7,9);var today = new Date();if (myDate>today){alert("Today is before 9th August 2008");}else{alert("Today is after 9th August 2008");}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.