Sle*_*er9 5 java apache-commons-lang apache-commons-dateutils
我正在使用Apache commons-lang3 DateUtils.truncate(Calendar calendar, int field)方法来"切断"Calendar对象的不必要字段.现在当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
*/
Run Code Online (Sandbox Code Playgroud)
所以我认为这应该有用,但显然不行.有没有办法使用DateUtils截断日期到一周的第一天?
更新:
我在源代码中查找并发现该modify()方法(tuncate()在内部使用它),遍历一堆预定义字段以查找给定参数.现在这些领域是:
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}};
Run Code Online (Sandbox Code Playgroud)
可以看出,没有任何东西与CalendarWEEK-ish字段相关,所以我想我必须手动执行此操作...欢迎任何其他想法/建议!
以合理的方式缩短一周实际上是不可能的。考虑以下日期:
2014-11-01 12:01:55
2014-11-01 12:01:00 // truncate minute
2014-11-01 00:00:00 // truncate day
2014-11-00 00:00:00 // truncate month
Run Code Online (Sandbox Code Playgroud)
原定日期是星期六。那么在这种情况下周截断意味着什么呢?我们应该截断到上周一吗?如果是这样的话,那就是:
2014-10-27 00:00:00 // truncate week?
Run Code Online (Sandbox Code Playgroud)
这对我来说似乎不对。在这种情况下,我们更改了月份;有时甚至年份也会改变。如果您能想出一种合理的方式来描述这一点(以及一些用例),请提出问题,我们将予以查看。但在我看来,它是一个没有任何截断意义的字段。
您可能会在这里找到解决原始问题的一些想法:检索本周的星期一日期
| 归档时间: |
|
| 查看次数: |
5706 次 |
| 最近记录: |