MonthDisplayHelper.NumberOfDaysInMonth returning i

2019-07-06 17:17发布

问题:

I would like to create a Calendar, but the MonthDisplayHelper return incorrect value (31 for 2013 February, which is 28 day). What am I doing wrong?

DateTime mRightNow = DateTime.Now;
MonthDisplayHelper mHelper = new MonthDisplayHelper(mRightNow.Year, mRightNow.Month, 2);
Log.Info("cal", mHelper.NumberOfDaysInMonth);

回答1:

You're mixing .Net and Java DateTime classes!

.Net months are 1-based

Java months are 0-based

So DateTime.Now is .Net and returning some day in the 2nd Month (February)

But MonthDisplayHelper is in Java and so is interpreting 2 as the 3rd Month (March)


Fix this by using mRightNow-1

Perhaps consider making this more readable using an Extension Method

public static class JavaDateTimeExtensions
{
    public static int JavaMonth(this DateTime input)
    {
        return input.Month - 1;
    }
}