简体   繁体   中英

get number of days in month with time4j

Is there a way to get number of days in a month using time4j lib?
in android default calendar, we can get it so simple like below

Calendar calendar=Calendar.getInstance();
int numOfDaysInMonth=calendar.getActualMaximum(Calendar.DAY_OF_MONTH);      

I mean a standard way, not crazy ways like going to the first Day of next month then come back one day and get day of month.
so can we do that in time4j calendars like "PersianCalendar"

The answer of @محمد علی using the default maximum has a problem: It does not use any calendar context so the maximum in leap years cannot be determined for the last month ESFAND. But the old comment given by @Tunaki is already a good and simple answer:

PersianCalendar today = PersianCalendar.nowInSystemTime();
int lengthOfCurrentMonth = today.lengthOfMonth();

Alternatively, you can also use the element PersianCalendar.DAY_OF_MONTH but then you should determine the contextual maximum, not the default maximum:

PersianCalendar today = PersianCalendar.nowInSystemTime();
int lengthOfCurrentMonth = today.getMaximum(PersianCalendar.DAY_OF_MONTH);

Both expressions will yield the same results in all ways and are completely equivalent.

For standard months (FARVARDIN (1) until BAHMAN (11)) the results will agree with the default maximum. But the last month ESFAND has either 29 days in normal years or 30 days in leap years. Both methods presented here will take this into account (but not the default maximum method).

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