傳回兩個日期之間的間隔數。
語法
DateDiff(interval, date1, date2)
引數:
表格 11-10 間隔引數值
| 設定 | 描述 |
|---|---|
| yyyy | 年 |
| q | 季 |
| m | 月 |
| d | Day |
| w | 星期幾 |
| h | Hour |
| n | Minute |
| s | Second |
支援的日期格式:
MM-DD-YYYYMM/DD/YYYYDD-MM-YYYYDD/MM/YYYYYYYY-MM-DDYYYY/MM/DD支援的時間格式:
hh:mm:ss
備註
您可以使用 DateDiff 函式來判斷兩個日期之間有多少個指定的時間間隔。例如,您可以使用 DateDiff 來計算兩個日期之間的天數。
若要計算 date1 與 date2 之間的天數,您可以使用日 ("d")。如果 date1 參照的時間點晚於 date2,則 DateDiff 函式會傳回負數。
將 12 月 31 日與隔年 1 月 1 日進行比較時,即使只過了一天,年 ("yyyy") 的 DateDiff 仍會傳回 1。
下列範例使用 DateDiff 函式來顯示指定日期與今天之間的天數:
範例 1:
Function DiffADate(theDate)
DiffADate = "Days from today: " & DateDiff("d", Now, theDate)
End Function
範例 2:
Dim StartDate, EndDate, Difference
StartDate = "01/01/2025"
EndDate = "21/01/2025"
Difference = DateDiff("d", StartDate, EndDate)
'Output: 20
範例 3:
Dim StartDate, EndDate, Difference
StartDate = "01/01/2020"
EndDate = "01/01/2025"
Difference = DateDiff("yyyy", StartDate, EndDate)
'Output: 5
範例 4:
Dim StartDate, EndDate, Difference
StartDate = "21/01/2025"
EndDate = "21/03/2025"
Difference = DateDiff("m", StartDate, EndDate)
'Output: 2
範例 5:
Dim StartDate, EndDate, Difference
StartDate = "21/01/2025 08:00:00" ' Includes time component.
EndDate = "21/01/2025 18:00:00" ' Includes time component.
Difference = DateDiff("h", StartDate, EndDate)
'Output: 10
範例 6:
Dim StartDate, EndDate, Difference
StartDate = "21/01/2025 08:00:00" ' Includes time component.
EndDate = "21/01/2025 08:45:00" ' Includes time component.
Difference = DateDiff("n", StartDate, EndDate)
'Output: 45
範例 7:
Dim StartDate, EndDate, Difference
StartDate = "21/01/2025 08:45:00" ' Includes time component.
EndDate = "21/01/2025 08:45:50" ' Includes time component.
Difference = DateDiff("s", StartDate, EndDate)
'Output: 50