How to get the current quarter from the current date using C #

I am trying to get the current quarter from the current date and save it as an int first, and then after I get the current quarter, for example, say it is Q1, then I want to save Q1 as a string. I get an error message that reads like this: unrecognized local variable dt., Please help. thanks

DateTime dt; int quarterNumber = (dt.Month - 1) / 3 + 1; 
+6
source share
4 answers

Well, you do not specify the "current date" anywhere - you did not assign a value to your dt variable, which the compiler complains about. You can use:

 DateTime dt = DateTime.Today; 

Note that this will use the local time zone of the system - and the date depends on the time zone. For example, if you need the date of the current moment in UTC, you need:

 DateTime dt = DateTime.UtcNow.Date; 

Think very carefully about what you mean by today.

In addition, a slightly simpler alternative version of your calculation:

 int quarter = (month + 2) / 3; 
+20
source

It was a good start, I ended up using this line. It seemed simpler regarding the goal, instead of adding 2.

 Math.Ceiling(DateTime.Today.Month / 3m) 
+1
source

dt is currently set to null. You must initialize it with DateTime dt = DateTime.Now;

0
source

It is initialized to default(DateTime) , which is 1/1/0001 12:00:00 AM

0
source

All Articles