GregorianCalendar / 日历和设置 HOUR 字段的奇怪之处
我正在尝试创建一个“固定”时间(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。
任何人都可以解释一下这一点并帮助我找到修复方法(或替代的做事方式)吗?
I'm trying to create a 'fixed' time (midnight in 24 hour clock format, i.e., 00:00:00) to set as a string for a SQL SELECT query using the the following...
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()));
This is fine UNLESS the current time is PM. For example,
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
If I do this when the current time is between midnight and midday, (i.e., 00:00:00 -> 11:59:59 AM) then my hour in the formatted string is correctly set to 00. If I do it at any time after midday and before midnight then I get 12 for my hour and not 00.
Can anybody explain this and help me find a fix (or alternative way of doing things) please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要将
HOUR_OF_DAY
设置为0
而不是HOUR
从 API 文档:
You need to set
HOUR_OF_DAY
to0
instead ofHOUR
From the API docs: