4

我知道Sql Server 有一些方便的内置季度内容,但是 .Net 原生DateTime对象呢?加、减和遍历四分之一的最佳方法是什么?

使用 VB 特有的DateAdd()函数是一件坏事吗?例如:

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
4

5 回答 5

9

我知道您可以通过以下方式计算日期的四分之一:

Dim quarter As Integer = (someDate.Month - 1) \ 3 + 1

如果您使用的是 Visual Studio 2008,则可以通过查看Extension Methods来尝试将附加功能附加到 DateTime 类。

于 2008-09-19T15:26:34.487 回答
4

这个怎么样:

Dim nextQuarter As DateTime = DateTime.Now.AddMonths(3);
于 2008-09-19T15:18:45.393 回答
1

需要记住的一件事是,并非所有公司都会在一个月的最后一天结束他们的季度。

于 2008-09-19T15:48:03.500 回答
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
于 2013-01-04T16:08:49.347 回答
1

扩展马特布莱恩的回答:

Dim intQuarter As Integer = Math.Ceiling(MyDate.Month / 3)

不确定这是否会增加速度优势,但它看起来更清洁 IMO

于 2014-02-05T14:24:23.217 回答