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
  • 5,149
  • 38
  • 130
  • 197
  • 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,421,763
  • 867
  • 9,128
  • 9,194
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,607
  • 10
  • 66
  • 101
0

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

Christophe De Troyer
  • 2,852
  • 3
  • 30
  • 47
0

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

  • Not if it's a local variable; If it's a local, it's not initialised at all and the compiler will throw errors if you try to use it without initialising it, which is what's happening in the question. Only class fields are initialised to `default(DateTime)`. – Mog0 May 05 '23 at 10:43