How to work with quarters (quarterly dates) in ASP.Net using VB.Net 2.0?

I know that Sql Server has handy built-in quarterly stuff , but what about a .Net native DateTime object? What is the best way to add, subtract, and intersect neighborhoods?

Is it wrong to use the DateAdd () function for the VB function? eg:.

Dim nextQuarter As DateTime = DateAdd(DateInterval.Quarter, 1, DateTime.Now) 

Edit: Extension of @bslorence function:

 Public Shared Function AddQuarters(ByVal originalDate As DateTime, ByVal quarters As Integer) As Datetime Return originalDate.AddMonths(quarters * 3) End Function 

@Matt function extension:

 Public Shared Function GetQuarter(ByVal fromDate As DateTime) As Integer Return ((fromDate.Month - 1) \ 3) + 1 End Function 

Edit: here are some more features that were convenient:

 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
source share
5 answers

I know you can calculate a quarter of the date:

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

If you are using Visual Studio 2008, you can try adding additional features to the DateTime class by looking at Extension Methods .

+9
source

How about this:

 Dim nextQuarter As DateTime = DateTime.Now.AddMonths(3); 
+4
source

One thing to keep in mind is that not all companies finish their apartment on the last day of the month.

+1
source
 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 
+1
source

Extension on Matt Blaine Answer:

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

Not sure if this will add speed advantages or not, but it looks softer. IMO

+1
source

Source: https://habr.com/ru/post/1276934/


All Articles