<%
' 取得指定月份首尾日
Function MonthFirstDay(dt, monthOffset)
' monthOffset: -1=上月, 0=本月, 1=下月
MonthFirstDay = DateSerial(Year(dt), Month(dt) + monthOffset, 1)
End Function
Function MonthLastDay(dt, monthOffset)
' 下月 1 號減 1 天 = 本月最後一天
MonthLastDay = DateAdd("d", -1, DateSerial(Year(dt), Month(dt) + monthOffset + 1, 1))
End Function
' 使用範例
Dim today
today = Date()
Response.Write "本月第一天: " & MonthFirstDay(today, 0) & "
"
Response.Write "本月最後一天: " & MonthLastDay(today, 0) & "
"
Response.Write "上月第一天: " & MonthFirstDay(today, -1) & "
"
Response.Write "上月最後一天: " & MonthLastDay(today, -1) & "
"
Response.Write "下月第一天: " & MonthFirstDay(today, 1) & "
"
Response.Write "下月最後一天: " & MonthLastDay(today, 1) & "
"
%>
<%
Dim dt
dt = Now()
' 系統格式 (依伺服器地區設定)
Response.Write "General: " & FormatDateTime(dt, 0) & "
" ' vbGeneralDate
Response.Write "LongDate: " & FormatDateTime(dt, 1) & "
" ' vbLongDate
Response.Write "ShortDate: " & FormatDateTime(dt, 2) & "
" ' vbShortDate
Response.Write "LongTime: " & FormatDateTime(dt, 3) & "
" ' vbLongTime
Response.Write "ShortTime: " & FormatDateTime(dt, 4) & "
" ' vbShortTime
' 自訂固定格式 (不受地區設定影響)
Response.Write "ISO Date: " & Year(dt) & "-" & Right("0" & Month(dt), 2) & "-" & Right("0" & Day(dt), 2) & "
"
Response.Write "ISO DateTime: " & Year(dt) & "-" & Right("0" & Month(dt), 2) & "-" & Right("0" & Day(dt), 2) & " " & _
Right("0" & Hour(dt), 2) & ":" & Right("0" & Minute(dt), 2) & ":" & Right("0" & Second(dt), 2) & "
"
Response.Write "中文日期: " & Year(dt) & "年" & Month(dt) & "月" & Day(dt) & "日" & "
"
Response.Write "檔名安全: " & Year(dt) & Right("0" & Month(dt), 2) & Right("0" & Day(dt), 2) & "_" & _
Right("0" & Hour(dt), 2) & Right("0" & Minute(dt), 2) & Right("0" & Second(dt), 2) & "
"
%>
| 需求 | 運算式 |
|---|---|
| 本週一 (週日為週首) | DateAdd("d", 1 - Weekday(Date, vbSunday), Date) |
| 本週日 | DateAdd("d", 7 - Weekday(Date, vbSunday), Date) |
| 本季第一天 | DateSerial(Year(Date), Int((Month(Date)-1)/3)*3 + 1, 1) |
| 本季最後一天 | DateAdd("d", -1, DateSerial(Year(Date), Int((Month(Date)-1)/3)*3 + 4, 1)) |
| 今年第一天 | DateSerial(Year(Date), 1, 1) |
| 今年最後一天 | DateSerial(Year(Date), 12, 31) |
| 兩日期相差天數 | DateDiff("d", startDate, endDate) |
| 兩日期相差月數 | DateDiff("m", startDate, endDate) |
| 年齡計算 | DateDiff("yyyy", birthDate, Date) + IIf(FormatDateTime(birthDate, 2) > FormatDateTime(Date, 2), -1, 0) |
經典 ASP 無內建時區支援。建議:
GETUTCDATE() / DateAdd("h", -8, Now()) 假設 UTC+8)。Intl.DateTimeFormat 或伺服端查詢時差表)。