萬盛學電腦網

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

ASP 取得上月、本月、下月第一天與最後一天的日期運算

直接可用的運算式

將以下運算式直接內嵌於 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)
%>

應用場景

  • 報表預設日期區間(如「本月銷售報表」預設帶入本月首尾)。
  • SQL 查詢 WHERE 子句動態產生:WHERE OrderDate BETWEEN #<%=bounds(0)%># AND #<%=bounds(1)%>#
  • 行事曆元件預設顯示月份計算。

注意事項

  • 日期字串格式建議使用 YYYY-MM-DD(ISO 8601),跨地區設定最安全。
  • 若伺服器地區設定非中華民國,Date() 格式可能不同,建議統一用 Year/Month/Day 組合。
  • 跨年邊界(1月/12月)DateAdd 會自動處理年份遞增/遞減,無需特殊判斷。
copyright © 萬盛學電腦網 all rights reserved