我正在尝试创建一个“固定”时间(24 小时时钟格式的午夜,即 00:00:00)以使用以下命令设置为 SQL SELECT 查询的字符串...
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
GregorianCalendar todayDate = new GregorianCalendar();
Log.d(TAG, "todayDate: " + todayDate.getTime().toString());
Log.d(TAG, "formatted todayDate: " + sdf.format(todayDate.getTime()));
todayDate.clear(Calendar.HOUR);
todayDate.clear(Calendar.MINUTE);
todayDate.clear(Calendar.SECOND);
todayDate.set(Calendar.HOUR, 0);
todayDate.set(Calendar.MINUTE, 0);
todayDate.set(Calendar.SECOND, 0);
Log.d(TAG, "formatted modified todayDate: " + sdf.format(todayDate.getTime()));
这很好,除非当前时间是下午。例如,
todayDate: Fri Jan 28 23:34:34 GMT 2011
formatted todayDate: 2011-01-28 23:34:34
formatted modified todayDate: 2011-01-28 12:00:00 <- THE hour is 12 not 00
如果我在当前时间介于午夜和中午之间(即 00:00:00 -> 11:59:59 AM)时执行此操作,那么我在格式化字符串中的小时将正确设置为 00。如果我这样做在中午之后和午夜之前的任何时间,我的小时数为 12,而不是 00。
谁能解释一下并帮助我找到解决方法(或替代方法)?
最佳答案
您需要将 HOUR_OF_DAY
设置为 0
而不是 HOUR
todayDate.set(Calendar.HOUR_OF_DAY, 0);
来自 API docs :
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.
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.
关于android - GregorianCalendar/Calendar 和设置 HOUR 字段奇数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4823721/