简体   繁体   中英

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?

DateTime.Month is a value between 1 and 12, which aligns with what most people think a month 'number' is.

Per the android docs , the DatePickerDialog constructor you are calling accepts a zero-based month. It accepts values in the range 0-11, so you need to subtract one from the DateTime.Month .

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM