【发布时间】:2014-10-04 15:44:04
【问题描述】:
我有以下代码:
Date now = CalendarUtils.getCalendar(getDefaultTimeZone())
.getTime();
CalendarUtils 类有以下方法
public static Calendar getCalendar(final TimeZone tz) {
return getCalendar(CalendarUtils.getDate(), tz);
}
public static Calendar getCalendar(final Date time, final TimeZone tz) {
final GregorianCalendar calendar = new GregorianCalendar();
calendar.setTimeZone(tz);
calendar.setTime(time);
return calendar;
}
public static Date getDate() {
return CalendarUtils.getDate(System.currentTimeMillis());
}
其中 getDefaultTimeZone() 返回特定时区中的时区对象。比如说欧洲/马德里。
但是,我的应用程序正在罗马的服务器上运行。
问题是上面的代码是用来获取马德里当地时间的。因此,8 月 8 日罗马的上午 12:30 仍然是马德里的 8 月 7 日晚上 11:30。
当我使用时
Date startOfDay = DateUtils.truncate(now, Calendar.DATE);
我希望 8 月 7 日 00:00:00 而不是 8 月 8 日 00:00:00
我已经阅读了 Date 如何从 Epoch 返回 Millis,但我希望它会从我从日历中询问的日期的 Epoch 返回 Millis。
当我在罗马时间 8 月 8 日凌晨 12:30 使用以下查询时,利用两个日期(现在和 startOfDay)我得到了 8 月 8 日而不是 7 日(马德里当地时间)的结果。
public BigInteger getSumForDates(Date fromDate, Date toDate) {
Session session = sessionFactory.openSession();
BigInteger sum;
try{
sum = (BigInteger)session
.createSQLQuery(
"SELECT SUM(column) FROM table
WHERE (column2 at time zone vas_tz()) >=:fromDate
AND (column2 at time zone vas_tz()) < :toDate")
.setTimestamp("fromDate", fromDate)
.setTimestamp("toDate", toDate).uniqueResult();
}catch (final HibernateException e){
LOGGER.error(e.getMessage());
throw new ProjectRuntimeException();
}finally{
session.close();
}
编辑
DateUtils 来自package org.apache.commons.lang.time;
public static Date truncate(Date date, int field) {
if (date == null) {
throw new IllegalArgumentException("The date must not be null");
}
Calendar gval = Calendar.getInstance();
gval.setTime(date);
modify(gval, field, MODIFY_TRUNCATE);
return gval.getTime();
}
当我说要返回我询问 Calendar 的日期的毫秒时,我的意思是如果日历提供了 8 月 7 日晚上 11:30 (因为我提供了时区),那么我希望毫秒来自8 月 7 日 11:30 之前的 Epoch 已针对该时区进行了调整。这是不正确的期望吗?
【问题讨论】:
-
@DavidPostill 这个问题更多地与打印格式正确的日期有关,这与我正在寻找的日期有点不同。