【问题标题】:get number of days in month with time4j使用 time4j 获取月份中的天数
【发布时间】:2017-03-01 19:19:39
【问题描述】:
有没有办法使用 time4j lib 获取一个月中的天数?
在android默认日历中,我们可以像下面这样简单
Calendar calendar=Calendar.getInstance();
int numOfDaysInMonth=calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
我的意思是一种标准的方式,而不是疯狂的方式,比如去下个月的第一天然后回来一天得到一个月的日期。
那么我们可以在诸如“PersianCalendar”之类的 time4j 日历中做到这一点
【问题讨论】:
标签:
java
android
date
time4j
【解决方案1】:
@محمد علی 使用默认最大值的答案有一个问题:它不使用任何日历上下文,因此无法确定上个月 ESFAND 的闰年最大值。但是@Tunaki 给出的旧评论已经是一个很好且简单的答案:
PersianCalendar today = PersianCalendar.nowInSystemTime();
int lengthOfCurrentMonth = today.lengthOfMonth();
或者,您也可以使用元素PersianCalendar.DAY_OF_MONTH,但您应该确定上下文最大值,而不是默认最大值:
PersianCalendar today = PersianCalendar.nowInSystemTime();
int lengthOfCurrentMonth = today.getMaximum(PersianCalendar.DAY_OF_MONTH);
两个表达式在所有方面都会产生相同的结果,并且完全等价。
对于标准月份(FARVARDIN (1) 到 BAHMAN (11)),结果将与默认最大值一致。但是最后一个月 ESFAND 要么在正常年份有 29 天,要么在闰年有 30 天。这里介绍的两种方法都会考虑到这一点(但不是默认的最大值方法)。