通过日历获取当天的最后时间会给出错误的结果
Getting the last time for the current day via the Calendar gives a wrong result
我正在尝试获取当天的最后时间。
例如:
今天的最后时间是 10.07.2015 23:59:59:999
因此我写了下面的方法:
private static Date getLastDateOfDay() {
final Calendar cal = Calendar.getInstance();
cal.set(Calendar.MILLISECOND, 999);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.HOUR, 23);
return cal.getTime();
}
这应该获取当前日期然后设置:
还有 23 小时
分钟到 59
秒到 59
毫秒到 999
所以这应该给我今天的最后一毫秒。
但是当我像这样使用这种方法时:
Date date = getLastDateOfDay();
那么日期的值为:11.07.2015 23:59:59:999
我错过了什么吗?我做错了什么吗?
请帮我解决一下这个。
提前致谢。
您可以尝试为您的日历实例设置明确的时区,即:
final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC");
这个答案也可以帮助:
What is the default timezone for java.util.Calendar.?
设置
cal.set(Calendar.HOUR_OF_DAY, 23);
您不能将 Hour 与 23 一起使用
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.
我正在尝试获取当天的最后时间。
例如:
今天的最后时间是 10.07.2015 23:59:59:999
因此我写了下面的方法:
private static Date getLastDateOfDay() {
final Calendar cal = Calendar.getInstance();
cal.set(Calendar.MILLISECOND, 999);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.HOUR, 23);
return cal.getTime();
}
这应该获取当前日期然后设置:
还有 23 小时
分钟到 59
秒到 59
毫秒到 999
所以这应该给我今天的最后一毫秒。
但是当我像这样使用这种方法时:
Date date = getLastDateOfDay();
那么日期的值为:11.07.2015 23:59:59:999
我错过了什么吗?我做错了什么吗?
请帮我解决一下这个。
提前致谢。
您可以尝试为您的日历实例设置明确的时区,即:
final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC");
这个答案也可以帮助: What is the default timezone for java.util.Calendar.?
设置
cal.set(Calendar.HOUR_OF_DAY, 23);
您不能将 Hour 与 23 一起使用
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.