我正在尝试创建一个涵盖整个月的日期范围,即
[开始日期;结束日期]
因此,我有一个引用日期并尝试从中创建一个新日期。我对“endDate”有疑问,因为我希望它接近一天结束时(即 23:59:59)。
我使用的代码如下:
public static Date previousMonthLastDate(Date referenceDate) {
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
calendar.setTime(referenceDate);
calendar.add(Calendar.MONTH, -1); // move to the previous month
int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.set(Calendar.DAY_OF_MONTH, lastDay);
// set the time to be the end of the day
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
return calendar.getTime();
}
此代码在 Android 模拟器 上按预期运行。但是,在真实手机上运行它会给出错误的日期。因此,我假设这是某种时区问题。
在电话中,不是说 31/August/2010,而是说 01/September/2010。该值接缝设置在将 HOUR_OF_DAY 设置为 23 的代码行之后。
有什么想法吗?
谢谢。
最佳答案
我无法回答为什么会这样,但是您是否尝试过将其设置为下个月的第一天并减去一秒/毫秒?
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.add(Calendar.MILLISECOND, -1);
关于Java月最后一天问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3672052/