我正在使用Apache commons-lang3 DateUtils.truncate(Calendar calendar, int field)
方法来“切断”日历对象的不必要字段。现在,当field
参数获取 的值时Calendar.WEEK_OF_MONTH
,它会抛出一个
java.lang.IllegalArgumentException: The field 4 is not supported
该truncate()
方法的文档说:
/**
* <p>Truncates a date, leaving the field specified as the most
* significant field.</p>
*
* <p>For example, if you had the date-time of 28 Mar 2002
* 13:45:01.231, if you passed with HOUR, it would return 28 Mar
* 2002 13:00:00.000. If this was passed with MONTH, it would
* return 1 Mar 2002 0:00:00.000.</p>
*
* @param date the date to work with, not null
* @param field the field from {@code Calendar} or <code>SEMI_MONTH</code>
* @return the different truncated date, not null
* @throws IllegalArgumentException if the date is <code>null</code>
* @throws ArithmeticException if the year is over 280 million
*/
所以我认为这应该可行,但显然不行。有没有办法使用 DateUtils 将日期截断为一周的第一天?
更新:
我在源代码中查找并发现该modify()
方法(tuncate()
在内部使用 this)遍历了一堆预定义的字段以找到给定的参数。现在这些字段是:
private static final int[][] fields = {
{Calendar.MILLISECOND},
{Calendar.SECOND},
{Calendar.MINUTE},
{Calendar.HOUR_OF_DAY, Calendar.HOUR},
{Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.AM_PM
/* Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH */
},
{Calendar.MONTH, DateUtils.SEMI_MONTH},
{Calendar.YEAR},
{Calendar.ERA}};
正如人们所看到的,与Calendar
WEEK 的字段没有任何关系,所以我想我必须手动执行此操作......欢迎任何其他想法/建议!