將以下運算式直接內嵌於 ASP 頁面(<%= ... %>)即可輸出對應日期:
| 描述 | 運算式 | 輸出範例(假設今日 2024-05-20) |
|---|---|---|
| 上月第一天 | DateAdd("m", -1, Year(Date) & "-" & Month(Date) & "-1") | 2024-04-01 |
| 上月最後一天 | DateAdd("d", -1, Year(Date) & "-" & Month(Date) & "-1") | 2024-04-30 |
| 本月第一天 | Year(Date) & "-" & Month(Date) & "-1" | 2024-05-01 |
| 本月最後一天 | DateAdd("d", -1, DateAdd("m", 1, Year(Date) & "-" & Month(Date) & "-1")) | 2024-05-31 |
| 下月第一天 | DateAdd("m", 1, Year(Date) & "-" & Month(Date) & "-01") | 2024-06-01 |
| 下月最後一天 | DateAdd("d", -1, DateAdd("m", 2, Year(Date) & "-" & Month(Date) & "-01")) | 2024-06-30 |
Year(Date) & "-" & Month(Date) & "-1" 組出「本月 1 號」字串,VBScript 自動轉為日期型別。DateAdd("m", -1, ...) 往前推一個月 → 上月 1 號。DateAdd("d", -1, 本月1號) 往前一天 → 上月最後一天。DateAdd("m", 1, 本月1號) → 下月 1 號;再 DateAdd("d", -1, ...) → 下月最後一天。<%
Function MonthBounds(refDate, offsetMonth)
' offsetMonth: -1=上月, 0=本月, 1=下月
Dim firstDay, lastDay
firstDay = DateAdd("m", offsetMonth, Year(refDate) & "-" & Month(refDate) & "-1")
lastDay = DateAdd("d", -1, DateAdd("m", 1, firstDay))
MonthBounds = Array(firstDay, lastDay)
End Function
' 使用範例
Dim bounds
bounds = MonthBounds(Date(), -1) ' 上月
Response.Write "上月: " & bounds(0) & " ~ " & bounds(1) & "<br>"
bounds = MonthBounds(Date(), 0) ' 本月
Response.Write "本月: " & bounds(0) & " ~ " & bounds(1) & "<br>"
bounds = MonthBounds(Date(), 1) ' 下月
Response.Write "下月: " & bounds(0) & " ~ " & bounds(1)
%>
WHERE OrderDate BETWEEN #<%=bounds(0)%># AND #<%=bounds(1)%>#YYYY-MM-DD(ISO 8601),跨地區設定最安全。Date() 格式可能不同,建議統一用 Year/Month/Day 組合。DateAdd 會自動處理年份遞增/遞減,無需特殊判斷。