java - Apache DateUtils 截断一周

标签 java apache-commons-lang apache-commons-dateutils

我正在使用 Apache commons-lang3 DateUtils.truncate(Calendar calendar, int field) 方法来“切断”日历对象的不必要字段。现在,当 field 参数获取 Calendar.WEEK_OF_MONTH 的值时,它会抛出一个

java.lang.IllegalArgumentException: 不支持字段 4

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() 内部使用了这个),遍历一堆预定义的字段来找到给定的参数。现在这些字段是:

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-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

原日期是星期六。那么周截断在那种情况下意味着什么?我们应该截断到前一个星期一吗?如果是这样,那就是:

2014-10-27 00:00:00 // truncate week?

我觉得这不对。在这种情况下,我们改变了月份;有时甚至年份都会改变。如果您能想到一种合理的方式来描述这一点(以及一些用例),请 file an issue我们会看一看。但我觉得它是一个对截断没有意义的字段。

您可能会在这里找到一些解决原始问题的想法:Retrieve current week's Monday's date

关于java - Apache DateUtils 截断一周,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26672030/

相关文章:

java - 本地存储与 SQLite?

java - 显式加载实体的集合

java - Apache Commons 包中的 IntegerUtils 和 DoubleUtils

java - 为什么 commons-lang 不在 java 标准 API 中?

java - 为什么apache commons lang是 "lang",lang代表语言吗?

java - DateUtils.parseDate 异常

Java Jar 无法在 Android 中运行

java - Eclipse插件开发: Vertically scrolling table?