萬盛學電腦網

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

ASP 常用日期時間操作速查:本月/上月/下月首尾日、格式化、週期計算

核心日期運算函數

<%
' 取得指定月份首尾日
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) & "
" %>

DateSerial 函數優勢

  • 直接以數值指定年、月、日,自動處理跨月/跨年(如 Month=13 會自動進位到次年 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 無內建時區支援。建議:

  1. 資料庫統一儲存 **UTC** 時間 (GETUTCDATE() / DateAdd("h", -8, Now()) 假設 UTC+8)。
  2. 顯示時依使用者偏好時區轉換 (前端 JS Intl.DateTimeFormat 或伺服端查詢時差表)。
copyright © 萬盛學電腦網 all rights reserved