简体   繁体   中英

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

I'm trying to write a function which involves checking if the current date is the first of the month such as 01/03/2015 for example and then run something depending if it is.

It doesn't matter whether it is a date or calendar object, I just want to check if the current date when the code is run is the first of the month

There's a getter for that:

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

Java 8 solution with LocalDate and TemporalAdjuster

first day of month:

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

last day of month:

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

This solution uses TemporalAdjusters utility from java.time.temporal . It is common practice to use it as import static but you can also use it as TemporalAdjusters.lastDayOfMonth()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM