我在 Java 中重置小时数时遇到问题。对于给定的日期,我想将小时数设置为 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
查询失败。
我知道 12:00:00 == 00:00:00
!
我正在使用 AppEngine。这是 appengine 错误、问题还是其他问题?还是依赖于别的东西?
最佳答案
使用另一个常量代替 Calendar.HOUR
,使用 Calendar.HOUR_OF_DAY
.
calendar.set(Calendar.HOUR_OF_DAY, 0);
Calendar.HOUR
使用 0-11(用于 AM/PM),Calendar.HOUR_OF_DAY
使用 0-23。
引用 Javadocs:
public static final int HOUR
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
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.
测试(“现在”目前是太平洋夏令时间 2013 年 7 月 23 日 14:55 左右):
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
关于java - 将时间设置为 00 :00:00,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17821601/