将时间设置为00:00:00
我在重置Java时遇到了问题。对于给定的日期,我想将小时数设置为00:00:00。
I have a problem resetting hours in Java. For a given date I want to set the hours to 00:00:00.
这是我的代码:
/**
* Resets milliseconds, seconds, minutes and hours from the provided date
*
* @param date
* @return
*/
public static Date trim(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR, 0);
return calendar.getTime();
}
问题是有时候时间 12: 00:00
,有时它是 00:00:00
当我在数据库中查询保存在 07.02.2013 00:00:00
并且存储的实际实体时间是 12:00:00
查询失败。
The problem is that sometimes the time is 12:00:00
and sometimes it is 00:00:00
and when I query the database for an entity that was saved on 07.02.2013 00:00:00
and the actual entity time, that is stored, is 12:00:00
the query fails.
我知道 12:00:00 == 00:00:00
!
我正在使用AppEngine。这是一个appengine bug,问题还是其他一些问题?或者它取决于其他什么?
I am using AppEngine. Is this an appengine bug, problem or some other issue? Or does it depend on something else?
使用另一个常量而不是 Calendar.HOUR
,使用 Calendar.HOUR_OF_DAY
。
Use another constant instead of Calendar.HOUR
, use Calendar.HOUR_OF_DAY
.
calendar.set(Calendar.HOUR_OF_DAY, 0);
Calendar.HOUR
使用0-11(用于AM / PM), Calendar.HOUR_OF_DAY
使用0-23。
Calendar.HOUR
uses 0-11 (for use with AM/PM), and Calendar.HOUR_OF_DAY
uses 0-23.
引用Javadoc:
To quote the Javadocs:
public static final int HOUR
public static final int HOUR
get和set的字段编号,表示
上午或下午的小时。 HOUR用于12小时
时钟(0 - 11)。中午和午夜由0表示,而不是由12.
例如,在10:04:15.250 PM,HOUR为10.
Field number for get and set indicating the hour of the morning or afternoon. HOUR is used for the 12-hour clock (0 - 11). Noon and midnight are represented by 0, not by 12. E.g., at 10:04:15.250 PM the HOUR is 10.
和
public static final int HOUR_OF_DAY
public static final int HOUR_OF_DAY
get的字段编号并设置
表示当天的小时。 HOUR_OF_DAY用于24小时
时钟。例如,在下午10:04:15.250,HOUR_OF_DAY为22。
Field number for get and set indicating the hour of the day. HOUR_OF_DAY is used for the 24-hour clock. E.g., at 10:04:15.250 PM the HOUR_OF_DAY is 22.
测试(现在目前为c.14:55 2013年7月23日太平洋夏令时):
Testing ("now" is currently c. 14:55 on July 23, 2013 Pacific Daylight Time):
public class Main
{
static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args)
{
Calendar now = Calendar.getInstance();
now.set(Calendar.HOUR, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
System.out.println(sdf.format(now.getTime()));
now.set(Calendar.HOUR_OF_DAY, 0);
System.out.println(sdf.format(now.getTime()));
}
}
输出:
$ javac Main.java
$ java Main
2013-07-23 12:00:00
2013-07-23 00:00:00