CalendarUtil.addMonthsToDate()和JsDate.setMonth()在GWT中给出错误的日期

问题描述 投票:0回答:1

如果是上个月结束日期是2018年8月31日,我想获得最后三个月的结束日期,即2018年6月30日,但是使用CalendarUtil.addMonthsToDate()和JsDate的setMonth()这两个API给我的日期是2018年7月1日。有关详细信息,请参阅以下代码:

Date currentMonthFirstDate = new Date();
CalendarUtil.setToFirstDayOfMonth(currentMonthFirstDate);//1-Sep

//Setting the Last month end date
final Date lastMonthEndDate = CalendarUtil.copyDate(currentMonthFirstDate);
CalendarUtil.addDaysToDate(lastMonthEndDate, -1);//31st Aug

final Date lastThreeMonthEndDate = CalendarUtil.copyDate(lastMonthEndDate);
CalendarUtil.addMonthsToDate(lastThreeMonthEndDate, -2);//Setting to 1st Sep but I want 30th june

谁能建议我同样的解决方案。因此,无论月份是31天还是30天,我都会得到确切的日期。

PS:我不能在GWT客户端代码中使用java.util.Calendar。

gwt
1个回答
2
投票

你非常接近理想的结果:)

你找到了跳到月底的正确方法:setToFirstDayOfMonth,然后addDaysToDate(-1天)将带你到上个月的最后一天。

如果你看一下addMonthsToDate方法的实现,你会发现它没有检查给定月份中的天数。因此,您可以获得Feb 30thJun 31st等无效日期。当然,这些日期将分别自动固定为Mar 2ndJul 1st

所以你不能在这种情况下使用addMonthsToDate方法。但是你已经知道如何获得上个月的最后一天 - 只需再使用它两次就能得到lastThreeMonthEndDate

Date currentMonthFirstDate = new Date();
CalendarUtil.setToFirstDayOfMonth(currentMonthFirstDate);   //1st Sep

//Setting the Last month end date
final Date lastMonthEndDate = CalendarUtil.copyDate(currentMonthFirstDate);
CalendarUtil.addDaysToDate(lastMonthEndDate, -1);           //31st Aug

final Date lastThreeMonthEndDate = CalendarUtil.copyDate(lastMonthEndDate);
CalendarUtil.setToFirstDayOfMonth(lastThreeMonthEndDate);   //1st Aug
CalendarUtil.addDaysToDate(lastThreeMonthEndDate, -1);      //31st Jul
CalendarUtil.setToFirstDayOfMonth(lastThreeMonthEndDate);   //1st Jul
CalendarUtil.addDaysToDate(lastThreeMonthEndDate, -1);      //30th Jun

只是考虑:你可以安全地使用addMonthsToDate方法,前提是你先setToFirstDayOfMonth。这样你就不会得到无效的日期,因为一天1st对任何月份都有效。

© www.soinside.com 2019 - 2024. All rights reserved.