10

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;
moe
  • 4,909
  • 38
  • 123
  • 190
  • Possible duplicate of [How do I discover the quarter of a given date](https://stackoverflow.com/questions/8698303/how-do-i-discover-the-quarter-of-a-given-date) – Jim G. Jun 03 '19 at 13:19

4 Answers4

31

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;
Jon Skeet
  • 1,335,956
  • 823
  • 8,931
  • 9,049
1

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)
Nick Albrecht
  • 16,167
  • 9
  • 67
  • 98
0

dt is currently assigned null. You need to initialize it with DateTime dt = DateTime.Now;

Christophe De Troyer
  • 2,792
  • 2
  • 28
  • 42
0

It's initialised with the value of default(DateTime) which has the value of 1/1/0001 12:00:00 AM