Raikoug Raikoug - 1 month ago 13
C# Question

DateTime month 0 invalid format

I'm having strange behavior of DateTime in c#.

I'm trying to initialize a datepicker in January. So I make a new date:

DateTime MyDate = new DateTime(2017, 0, 15);


But I get this exception:


System.ArgumentOutOfRangeException: Year, Month, and Day parameters describe an un-representable DateTime.


If I use
(2017, 1, 15)
it works but the time dialog, initialized with:

DatePickerDialog dialog = new DatePickerDialog(
Activity,
this,
MyDate.Year,
MyDate.Month,
MyDate.Day);


Goes on February.

Well I tried to "cheat" and did:

DateTime MyDate = new DateTime(2017, 1, 15);
DateTime = DateTime.AddMonths(-1);


No error, but the date picker goes on February.

The only way to have January is:

DateTime MyDate = new DateTime(2017, 12, 15);


What am I doing wrong?

L J L J
Answer

The issue is how the DateTime object treats month values (1-12) and how the DatePickerDialog treats month values (0-11).


DateTime constructor:

strange behavior of DateTime

DateTime MyDate = new DateTime(2017, 0, 15);

If we take a look at the DateTime constructor, it is clearly stated that the month value should be 1 through 12, which is not valid in your case and hence the exception. We can correct it as below:

DateTime MyDate = new DateTime(2017, 1, 15);

DatePickerDialog constructor:

Exception (or strange behavior) will arise when we try - new DatePickerDialog in combination with the month value of DateTime as the constructor of DatePickerDialog is expecting the month values from 0-11.

It is stated that int: the initially selected month (0-11 for compatibility with MONTH)

The approach which can then be followed is to give the correct index for month to DatePickerDialog constructor as below:

DateTime MyDate = new DateTime(2017, 1, 15);
DatePickerDialog dialog = new DatePickerDialog(Activity,
                                               this,
                                               MyDate.Year,
                                               MyDate.Month - 1,
                                               MyDate.Day);
Comments