如何检查当前日期是否是本月的第一天

How to check if the current date is the first of the month

我正在尝试编写一个函数,该函数涉及检查当前日期是否是本月的第一天,例如 01/03/2015,然后 运行 取决于它是否是。

无论是日期对象还是日历对象都无所谓,我只想检查代码为运行时的当前日期是否为月份的第一天

有一个getter:

public boolean isFirstDayofMonth(Calendar calendar){
    if (calendar == null) {
        throw new IllegalArgumentException("Calendar cannot be null.");
    }

    int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
    return dayOfMonth == 1;
}
public static boolean isFirstDayOfTheMonth(Date dateToday){
    Calendar c = new GregorianCalendar();
    c.setTime(dateToday );

    if (c.get(Calendar.DAY_OF_MONTH) == 1) {
      return true;
    }
    returns false;
}

Java 8 解决方案与 LocalDate 和 TemporalAdjuster

一个月的第一天:

someDate.isEqual(someDate.with(firstDayOfMonth()))

一个月的最后一天:

someDate.isEqual(someDate.with(lastDayOfMonth())

此解决方案使用 java.time.temporal 中的 TemporalAdjusters 实用程序。通常的做法是将其用作 import static,但您也可以将其用作 TemporalAdjusters.lastDayOfMonth()