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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With