萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 日期時間運算完全手冊:DateAdd、DateDiff、DatePart、FormatDateTime 實戰範例

前言

日期運算是商務邏輯核心 (到期日、週年、排程、統計區間)。VBScript 提供 `DateAdd`、`DateDiff`、`DatePart`、`FormatDateTime` 四大核心函數,本文系統整理語法、間隔單位、實戰範例與常見坑點。

核心間隔單位對照表 (Interval)

代碼中文英文範例值
yyyy年Year2024
q季度Quarter1~4
m月Month1~12
y年間第幾天DayOfYear1~366
d日Day1~31
w週內第幾天Weekday1 (週日) ~ 7 (週六)
ww週數WeekOfYear1~53
h小時Hour0~23
n分鐘Minute0~59
s秒Second0~59

1. DateAdd — 加減日期/時間

DateAdd(interval, number, date)
' number > 0 未來,< 0 過去

關鍵特性:自動處理月份天數差異、閏年

DateAdd("m", 1, "1995-01-31")  ' → 1995-02-28 (非閏年)
DateAdd("m", 1, "1996-01-31")  ' → 1996-02-29 (閏年)
DateAdd("d", -15, "2002-11-08") ' → 2002-10-24 (往前 15 天)

若計算結果早於西元 100 年,將拋出錯誤。`number` 非長整數時四捨五入。

實戰範例:計算會員到期日、排程觸發時間

Dim expiryDate, nextRun
expiryDate = DateAdd("m", 12, Date())      ' 會員一年到期
nextRun = DateAdd("n", 30, Now())          ' 30 分鐘後執行排程
Response.Write "到期日:" & expiryDate & "
下次執行:" & nextRun

2. DateDiff — 計算兩日期時間差

DateDiff(interval, date1, date2[, firstDayOfWeek[, firstWeekOfYear]])
' 回傳 date2 - date1 的間隔數 (有正負號)

實戰範例:會員註冊天數、逾期天數、年齡計算

Dim regDate, daysSinceReg, ageYears
regDate = #2020-05-15#
daysSinceReg = DateDiff("d", regDate, Date())  ' 註冊至今天數

' 年齡計算 (精確到生日)
Dim birthDate : birthDate = #1990-08-20#
ageYears = DateDiff("yyyy", birthDate, Date())
' 修正:若今年生日未到,減 1
If DateDiff("d", DateSerial(Year(Date()), Month(birthDate), Day(birthDate)), Date()) < 0 Then
    ageYears = ageYears - 1
End If
Response.Write "註冊天數:" & daysSinceReg & "
年齡:" & ageYears

3. DatePart — 擷取日期時間單一元件

DatePart(interval, date[, firstDayOfWeek[, firstWeekOfYear]])

實戰範例:按月/週分組統計、判斷週末

Dim currentMonth, currentWeekday
currentMonth = DatePart("m", Date())      ' 當前月份 (1-12)
currentWeekday = DatePart("w", Date())    ' 當前星期 (1=週日...7=週六)
If currentWeekday = 1 Or currentWeekday = 7 Then
    Response.Write "今天是週末"
End If

4. FormatDateTime — 格式化輸出

FormatDateTime(date[, namedFormat])
' namedFormat 常數:
' vbGeneralDate (0) : 預設,日期+時間 (短日期格式+長時間格式)
' vbLongDate    (1) : 長日期格式 (如 2024年1月15日)
' vbShortDate   (2) : 短日期格式 (如 2024/1/15)
' vbLongTime    (3) : 長時間格式 (如 14:30:00)
' vbShortTime   (4) : 短時間格式 (如 14:30)

實戰範例:多國語系顯示、報表匯出格式

Response.Write FormatDateTime(Now(), vbLongDate)   & " " & FormatDateTime(Now(), vbLongTime)
' 輸出:2024年1月15日 14:30:00
Response.Write FormatDateTime(Now(), vbShortDate)  & " " & FormatDateTime(Now(), vbShortTime)
' 輸出:2024/1/15 14:30

綜合實戰:動態產生行事曆/排程表

<%
' 產生指定年月的行事曆表格
Function RenderCalendar(year, month)
    Dim firstDay, daysInMonth, startWeekday, day, html, i
    firstDay = DateSerial(year, month, 1)
    daysInMonth = Day(DateSerial(year, month + 1, 0))  ' 下月 0 號 = 本月最後一天
    startWeekday = Weekday(firstDay)  ' 1=週日
    
    html = ""
    ' 補空白
    For i = 1 To startWeekday - 1
        html = html & ""
    Next
    
    For day = 1 To daysInMonth
        If startWeekday > 7 Then
            html = html & ""
            startWeekday = 1
        End If
        Dim isToday : isToday = (day = Day(Date()) And month = Month(Date()) And year = Year(Date()))
        html = html & "" & day & ""
        startWeekday = startWeekday + 1
    Next
    html = html & "
日一二三四五六
 
" RenderCalendar = html End Function Response.Write RenderCalendar(2024, 1) %>

常見坑點與避坑指南

坑點錯誤寫法正確寫法原因
字串當日期傳入DateAdd("d", 1, "2024-01-15")DateAdd("d", 1, CDate("2024-01-15")) 或 #2024-01-15#字串依地區設定解析,易誤判
Interval 大小寫DateAdd("M", 1, Date())DateAdd("m", 1, Date())區間代碼**區分大小寫**,m=月,M=分鐘(錯誤)
DateDiff 參數順序DateDiff("d", Date(), regDate)DateDiff("d", regDate, Date())回傳 date2 - date1,順序反則負數
Weekday 起始日假設 Weekday 1=週一Weekday 1=週日 (美國制),可用 firstDayOfWeek 參數調整預設 vbSunday=1
跨世紀兩位數年份CDate("99/12/31")CDate("1999/12/31") 或四位數年份兩位數年份閾值依系統設定 (通常 2029/2030)

結語

掌握 `DateAdd`/`DateDiff`/`DatePart`/`FormatDateTime` 四大函數與 10 種間隔單位,配合 `DateSerial`/`TimeSerial` 組合日期時間、`Weekday` 判斷週末、`MonthName`/`WeekdayName` 多語系顯示,即可處理 99% ASP 日期業務場景。核心原則:**傳遞 Date 型別變數,而非字串;間隔代碼區分大小寫;DateDiff 參數順序 = 起始、結束。**

copyright © 萬盛學電腦網 all rights reserved