如果您的数据层保存 UTC 时间但您的表示层有不同的时区并且您需要截断日期进行过滤,则以下功能很有用。
/**
* Truncates the given UTC date for the given TimeZone
*
* @param date UTC date
* @param timeZone Target timezone
* @param field Calendar field
*
* @return
*/
public static Date truncate(Date date, final TimeZone timeZone, final int field)
{
int timeZoneOffset = timeZone.getOffset(date.getTime());
// convert UTC date to target timeZone
date = DateUtils.addToDate(date, Calendar.MILLISECOND, timeZoneOffset);
// truncate in target TimeZone
date = org.apache.commons.lang3.time.DateUtils.truncate(date, field);
// convert back to UTC
date = DateUtils.addToDate(date, Calendar.MILLISECOND, -timeZoneOffset);
return date;
}
/**
* Adds the given amount to the given Calendar field to the given date.
*
* @see Calendar
*
* @param date the date
* @param field the calendar field to add to
* @param amount the amount to add, may be negative
*
* @return
*/
public static Date addToDate(final Date date, final int field, final int amount)
{
Objects.requireNonNull(date, "date must not be null");
final Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(field, amount);
return c.getTime();
}