Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 262
Nick Karaolis Avatar asked Mar 30 '15 13:03

Nick Karaolis


2 Answers

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;
}
like image 79
But I'm Not A Wrapper Class Avatar answered Oct 27 '22 14:10

But I'm Not A Wrapper Class


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

like image 6
Michal Maťovčík Avatar answered Oct 27 '22 16:10

Michal Maťovčík