首頁  >  問答  >  主體

如何計算兩個日期之間的天數?

<p>例如,輸入框中給出兩個日期:</p> <pre class="brush:php;toolbar:false;"><input id="first" value="1/1/2000"/> <input id="second" value="1/1/2001"/> <script> alert(datediff("day", first, second)); // what goes here? </script></pre> <p>如何在 JavaScript 中取得兩個日期之間的天數? </p>
P粉604848588P粉604848588423 天前497

全部回覆(2)我來回復

  • P粉968008175

    P粉9680081752023-08-24 14:38:40

    截至撰寫本文時,只有其他答案之一可以正確處理 DST(夏令時)轉換。以下是位於加利福尼亞州的系統上的結果:

    1/1/2013- 3/10/2013- 11/3/2013-
    User       Formula                      2/1/2013  3/11/2013  11/4/2013  Result
    ---------  ---------------------------  --------  ---------  ---------  ---------
    Miles                   (d2 - d1) / N   31        0.9583333  1.0416666  Incorrect
    some         Math.floor((d2 - d1) / N)  31        0          1          Incorrect
    fuentesjr    Math.round((d2 - d1) / N)  31        1          1          Correct
    toloco     Math.ceiling((d2 - d1) / N)  31        1          2          Incorrect
    
    N = 86400000

    雖然 Math.round 回傳正確的結果,但我認為它有點笨拙。相反,透過明確考慮 DST 開始或結束時 UTC 偏移量的變化,我們可以使用精確的算術:

    function treatAsUTC(date) {
        var result = new Date(date);
        result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
        return result;
    }
    
    function daysBetween(startDate, endDate) {
        var millisecondsPerDay = 24 * 60 * 60 * 1000;
        return (treatAsUTC(endDate) - treatAsUTC(startDate)) / millisecondsPerDay;
    }
    
    alert(daysBetween($('#first').val(), $('#second').val()));

    說明

    JavaScript 日期計算很棘手,因為 Date 物件在內部儲存 UTC 時間,而不是本機時間。例如,3/10/2013 12:00 AM 太平洋標準時間(UTC-08:00) 儲存為3/10/2013 8:00 AM UTC,3/11/2013 12:00 AM 太平洋夏令時間( UTC-07 :00) 儲存為3/11/2013 7:00 AM UTC。這一天,當地時間午夜到午夜僅比 UTC 23 小時!

    雖然當地時間的一天可以多於或少於 24 小時,但 UTC 的一天始終恰好是 24 小時。 1 上面顯示的daysBetween 方法利用了這一點透過先呼叫treatAsUTC 將兩個本地時間調整為午夜UTC,然後再進行減法和除法來了解這一事實。

    1。 JavaScript 忽略閏秒。

    回覆
    0
  • P粉186897465

    P粉1868974652023-08-24 12:44:32

    這裡是 datediff快速而骯髒的實現,作為解決問題中提出的問題的概念證明。它依賴於這樣一個事實:您可以透過減去兩個日期來獲取它們之間經過的毫秒數,這會將它們強制轉換為其原始數值(自 1970 年初以來的毫秒數)。

    /**
     * Take the difference between the dates and divide by milliseconds per day.
     * Round to nearest whole number to deal with DST.
     */
    function datediff(first, second) {        
        return Math.round((second - first) / (1000 * 60 * 60 * 24));
    }
    
    /**
     * new Date("dateString") is browser-dependent and discouraged, so we'll write
     * a simple parse function for U.S. date format (which does no error checking)
     */
    function parseDate(str) {
        var mdy = str.split('/');
        return new Date(mdy[2], mdy[0] - 1, mdy[1]);
    }
    
    alert(datediff(parseDate(first.value), parseDate(second.value)));
    <input id="first" value="1/1/2000"/>
    <input id="second" value="1/1/2001"/>

    回覆
    0
  • 取消回覆