Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Current Quarter from Current Date using C#

Tags:

c#

asp.net

I am trying to get the current quarter from current date and store it as int first, then after i get the current quarter like say it is Q1 then i want to store Q1 as string. I am getting an error that reads like this: unassigned local variable dt. . Please help. thanks

DateTime dt;
int quarterNumber = (dt.Month - 1) / 3 + 1;
like image 911
moe Avatar asked Jan 21 '14 19:01

moe


2 Answers

Well you're not specifying "the current date" anywhere - you haven't assigned a value to your dt variable, which is what the compiler's complaining about. You can use:

DateTime dt = DateTime.Today;

Note that that will use the system local time zone - and the date depends on the time zone. If you want the date of the current instant in UTC, for example, you'd want:

DateTime dt = DateTime.UtcNow.Date;

Think very carefully about what you mean by "today".

Also, a slightly simpler alternative version of your calculation would be:

int quarter = (month + 2) / 3;
like image 179
Jon Skeet Avatar answered Oct 06 '22 01:10

Jon Skeet


This was a good start, I ended up using this line. Seemed more straightforward as to the goal, instead of adding 2.

Math.Ceiling(DateTime.Today.Month / 3m)
like image 38
Nick Albrecht Avatar answered Oct 06 '22 02:10

Nick Albrecht