我在尝试使用日历时遇到问题。 看:
public static Calendar novaData(Calendar originDate, Integer amountMonth) {
System.out.println("Origin date: " + originDate.getTime() + " - Add " + amountMonth + " Months");
Calendar date = new GregorianCalendar(originDate.getTimeZone());
date.add(Calendar.MONTH, amountMonth);
System.out.println(date.getTime());
return date;
}
在此方法中,我将设置一个日期以及要添加到该日期的月份数。问题就在那里,这一天即将到来,就像今天(18 日)一样,而不是我过去的第一天。预计结果为 May/01/2019 - Jun/01/2019 - Jul/01/2019
最佳答案
java.time
LocalDate originDate = LocalDate.of(2019, Month.MAY, 1);
for (int amountMonth = 1; amountMonth <= 3; amountMonth++) {
System.out.println("Origin date: " + originDate + " - Add " + amountMonth + " Months");
System.out.println(originDate.plusMonths(amountMonth));
}
输出是:
Origin date: 2019-05-01 - Add 1 Months 2019-06-01 Origin date: 2019-05-01 - Add 2 Months 2019-07-01 Origin date: 2019-05-01 - Add 3 Months 2019-08-01
我从您想要的输出中了解到您只对日期感兴趣,而不是一天中的时间或时区。如果是这样,则 LocalDate
类是要使用的正确类。
如果您只对月份感兴趣,而不对月份中的日期感兴趣,请使用 YearMonth
而不是 LocalDate
。除了声明和初始化之外,代码将相同:
YearMonth originDate = YearMonth.of(2019, Month.MAY);
Origin date: 2019-05 - Add 1 Months 2019-06 (etc.)
不要使用日历
和GregorianCalendar
。这些类(class)设计得很差并且早已过时。最重要的是,它们为每个对象携带了一天中的时间、时区、一周计划等等,所有这些我认为您都不需要,而且这只会让那些阅读您代码的人感到困惑。
链接: Oracle tutorial: Date Time解释如何使用 java.time。
关于java - 使用日历的日期问题 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56201612/