我知道Sql Server has some handy built-in quarterly这些东西,但是.Net原生DateTime对象呢?添加,减去和遍历季度的最佳方法是什么?
使用特定于VB的DateAdd()函数是坏事™吗? e.g:
Dim nextQuarter As DateTime = DateAdd(DateInterval.Quarter, 1, DateTime.Now)
编辑: 扩展@ bslorence的功能:
Public Shared Function AddQuarters(ByVal originalDate As DateTime, ByVal quarters As Integer) As Datetime
Return originalDate.AddMonths(quarters * 3)
End Function
扩展@Matt的功能:
Public Shared Function GetQuarter(ByVal fromDate As DateTime) As Integer
Return ((fromDate.Month - 1) \ 3) + 1
End Function
编辑:这里还有一些方便的功能:
Public Shared Function GetFirstDayOfQuarter(ByVal originalDate As DateTime) As DateTime
Return AddQuarters(New DateTime(originalDate.Year, 1, 1), GetQuarter(originalDate) - 1)
End Function
Public Shared Function GetLastDayOfQuarter(ByVal originalDate As DateTime) As DateTime
Return AddQuarters(New DateTime(originalDate.Year, 1, 1), GetQuarter(originalDate)).AddDays(-1)
End Function
答案 0 :(得分:9)
我知道您可以通过以下方式计算日期的四分之一:
Dim quarter As Integer = (someDate.Month - 1) \ 3 + 1
如果您使用的是Visual Studio 2008,则可以通过查看Extension Methods来尝试将其他功能附加到DateTime类。
答案 1 :(得分:4)
这个怎么样:
Dim nextQuarter As DateTime = DateTime.Now.AddMonths(3);
答案 2 :(得分:1)
有一点需要记住,并非所有公司都在一个月的最后一天结束他们的宿舍。
答案 3 :(得分:1)
Public Function GetLastQuarterStart() As Date
GetLastQuarterStart = DateAdd(DateInterval.Quarter, -1, DateTime.Now).ToString("MM/01/yyyy")
End Function
Public Function GetLastQuarterEnd() As Date
Dim LastQuarterStart As Date = DateAdd(DateInterval.Quarter, -1, DateTime.Now).ToString("MM/01/yyyy")
Dim MM As String = LastQuarterStart.Month
Dim DD As Integer = 0
Dim YYYY As String = LastQuarterStart.Year
Select Case MM
Case "01", "03", "05", "07", "08", "10", "12"
DD = 31
Case "02"
Select Case YYYY
Case "2012", "2016", "2020", "2024", "2028", "2032"
DD = 29
Case Else
DD = 28
End Select
Case Else
DD = 30
End Select
Dim LastQuarterEnd As Date = DateAdd(DateInterval.Month, 2, LastQuarterStart)
MM = LastQuarterEnd.Month
YYYY = LastQuarterEnd.Year
Return String.Format("{0}/{1}/{2}", MM, DD, YYYY)
End Function
答案 4 :(得分:1)
扩展马特布莱恩的答案:
Dim intQuarter As Integer = Math.Ceiling(MyDate.Month / 3)
不确定这是否会增加速度效益,但IMO看起来更清晰