java - 使用日历的日期问题 - Java

标签 java calendar

我在尝试使用日历时遇到问题。 看:

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;
}

现在,控制台: enter image description here

在此方法中,我将设置一个日期以及要添加到该日期的月份数。问题就在那里,这一天即将到来,就像今天(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/

相关文章:

java - 将对象从一个 ArrayList 移动到另一个

java - Play!2.2.1 Java Ebean - Finder.select(String columns) 不起作用 : all the columns are selected

java - Hibernate:使用子选择和左外连接执行条件查询?

java - 无法理解Calendar类的before函数

ios - 如何在日历选择日期 Xcode 上添加文本

java - 我应该如何实现这个 HashMap 的 equals 和 hashCode 方法来表示自动机状态?

java - Intellij Idea 提示 : Condition is always false - can that be true here? (Java)

jquery - 基于MVC框架的Outlook风格事件日历项目

javascript - 用于从弹出式日历中选择日期的定期维护的 Javascript 库?

javascript - jCal 使用 jQuery