7

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

Nick Karaolis
  • 127
  • 1
  • 3
  • 13

3 Answers3

12

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

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()

2
public static boolean isFirstDayOfTheMonth(Date dateToday){
    Calendar cal = Calendar.getInstance();
    c.setTime(dateToday );

    if (c.get(Calendar.DAY_OF_MONTH) == 1) {
      return true;
    }
    return false;
}
Loïc Gammaitoni
  • 4,173
  • 16
  • 39
  • Generally better to use Calendar.getInstance() and let the JVM decide which Calendar to use rather than enforcing the use of GregorianCalendar – Loïc Gammaitoni Mar 20 '23 at 13:03