Does anyone know how to construct a DateTime in .NET to be the first day of the current quarter?
+2
A:
var currentTime = DateTime.Now;
var year = currentTime.Year;
DateTime[] quarterStarts = {new DateTime(year, 1, 1), new DateTime(year, 4, 1), new DateTime(year, 7, 1), new DateTime(year, 10, 1)};
var currentStart = quarterStarts.Where(s => s < currentTime).Last();
danijels
2010-09-30 18:31:23
This is going to fail if it's called exactly at 12:00 midnight on January 1. It's also going to fail if the year changes at some point after `quarterStarts` is defined. You probably want to modify your test to include just the month and day.
Jim Mischel
2010-09-30 19:37:36
+1
A:
@yogesh is right, here's what I use in a sql sp:
CREATE FUNCTION [dbo].[fn_startOfQtr](@dt DATETIME)
RETURNS DATETIME AS
BEGIN
declare @ret DATETIME
declare @qtr int
set @qtr = ((month(@dt)-1)/3)+1
set @ret = cast(str(@qtr * 3 - 2) + '/1/' + str(year(@dt)) as DATETIME)
return @ret
END
Beth
2010-09-30 18:31:55
+3
A:
public DateTime GetCurrentQuarter(DateTime date)
{
int startingMonthOfQuarter = (((date.Month - 1) / 3) * 3) + 1;
return new DateTime(date.Year, startingMonthOfQuarter, 1);
}
Yogesh
2010-09-30 18:55:07