You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据任意日期获取半年首尾日期?现有季度代码如何转换

获取指定日期对应半年的首尾日期(VB.NET)

需求说明

给定一年中的任意日期,获取其所属半年的首尾日期:

  • 上半年:1月1日 ~ 6月30日
  • 下半年:7月1日 ~ 12月31日

原用于获取季度首尾日期的代码如下:

'获取季度的第一天
Public Shared Function FirstDayOfQuarter(ByVal theDay As DateTime) As DateTime
    Dim currQuarter As Integer = (Month(theDay) - 1) \ 3 + 1
    Dim FirstDayQuarter As DateTime = DateSerial(Year(theDay), 3 * currQuarter - 2, 1)
    Return FirstDayQuarter
End Function
'获取季度的最后一天
Public Shared Function LastDayOfQuarter(ByVal theDay As DateTime) As DateTime
    Dim currQuarter As Integer = (Month(theDay) - 1) \ 3 + 1
    Dim LastDayQuarter As DateTime = DateSerial(Year(theDay), 3 * currQuarter + 1, 0)
    Return LastDayQuarter
End Function

修改后的半年首尾日期函数

1. 获取半年的第一天

'获取对应半年的第一天
Public Shared Function FirstDayOfHalfYear(ByVal theDay As DateTime) As DateTime
    If Month(theDay) <= 6 Then
        '上半年第一天为当年1月1日
        Return DateSerial(Year(theDay), 1, 1)
    Else
        '下半年第一天为当年7月1日
        Return DateSerial(Year(theDay), 7, 1)
    End If
End Function

2. 获取半年的最后一天

'获取对应半年的最后一天
Public Shared Function LastDayOfHalfYear(ByVal theDay As DateTime) As DateTime
    If Month(theDay) <= 6 Then
        '利用DateSerial特性:传入0日会返回上月最后一天,这里返回6月30日
        Return DateSerial(Year(theDay), 7, 0)
    Else
        '返回12月31日
        Return DateSerial(Year(theDay), 13, 0)
    End If
End Function

逻辑说明

  • 通过判断日期的月份是否≤6,直接区分上下半年,逻辑比季度计算更简洁。
  • 借助DateSerial的内置特性处理月末日期:当日期参数为0时,自动返回上一个月的最后一天,无需手动判断每月天数,完美兼容闰年的2月、大月小月差异。

内容的提问来源于stack exchange,提问作者icm63

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 17:55:20