[英]How to find Days difference between two dates using javascript
我需要使用JavaScript查找兩個日期之間的天差,這是我的代碼
我有開始日期和結束日期
var diff = Math.floor((Date.parse(enddate) - Date.parse(startdate)) / 86400000);
它計算與當前時間的差。 我需要找到給定日期之間的日期數。
例如,如果我輸入的開始日期為2014年12月17日和2014年12月19日,則顯示兩天,但是我需要計算天數17,18和19。它應顯示為三天。
有人可以幫我嗎?
您可以在進行比較之前將小時,分鍾,秒和毫秒設置為0,以忽略一天中的時間,例如:
var startdate = "2014-12-17"; var enddate = "2014-12-19"; var start = new Date(startdate); start.setHours(0, 0, 0, 0); // Sets hours, minutes, seconds, and milliseconds var end = new Date(enddate); end.setHours(0, 0, 0, 0); var diff = Math.round((end - start) / 86400000) + 1; // See note below re `+ 1` snippet.log("diff = " + diff); // 3
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
關於這兩個注意事項:
Math.round
:這是在這里,因為如果時間跨度超過了夏令時邊界,則該數字將減少一小部分,但會在舍入校正范圍內。 請注意,您必須舍入 ,截斷地板,天花板,而不要截斷。
+ 1
: diff =
行末尾的+ 1
是因為您的“差異”是不尋常的,因為您要計算開始和結束的天數。 這很奇怪,它會說從一個星期一到下一個星期一的天數差是8個 ,而不是7天,因為它將算在任一端的星期一。 但是你說:
例如,如果我輸入的開始日期為2014年12月17日和2014年12月19日,則顯示的是兩天,但我需要計算出天數17,18和19。
...所以您需要+ 1
。 兩個日期之間沒有正常的區別。
跨DST邊界的示例(在許多時區中):
var start, end, diff; start = new Date(2014, 2, 1); // March 1st 2014 end = new Date(2014, 5, 1); // May 1st 2014 diff = ((end - start) / (1000 * 3600 * 24)) + 1; // diff won't *quite* be 93, because of the change to DST // (assuming a timezone where DST changes sometime in // March, as in most parts of the US, UK, and Canada snippet.log("diff = " + diff + " instead of 93"); snippet.log("rounded = " + Math.round(diff)); // Similarly, at the other end: start = new Date(2014, 9, 1); // October 1st 2014 end = new Date(2014, 11, 1); // December 1st 2014 diff = ((end - start) / (1000 * 3600 * 24)) + 1; // diff won't *quite* be 62, because of the change to DST // (assuming a timezone where DST changes sometime in // March, as in most parts of the US, UK, and Canada snippet.log("diff = " + diff + " instead of 62"); snippet.log("rounded = " + Math.round(diff));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
這種事情使我轉向像MomentJS
這樣的庫。 使用MomentJS,它將是:
var diff = moment(enddate).diff(moment(startdate), 'days') + 1;
... + 1
再次是因為您對兩個日期之間的時差的不尋常定義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.