Juanjo
Juanjo

Reputation: 969

Get first Monday and last Sunday of Month, crossing Month boundary

I want to get the first Monday and the last Sunday that are in the weeks overlapping the current month, even if the Monday or the Sunday aren't from the current month.

For example, this month 2017-04 (April), the first Monday is March 27 and the last Sunday April 30.

Upvotes: 1

Views: 1568

Answers (3)

Basil Bourque
Basil Bourque

Reputation: 338775

The TemporalAdjuster interface provides for classes to manipulate date-time values. The TemporalAdjusters class provides several handy implementations.

The strategy is to first determine the current date. That requires a time zone. For any given moment, the date varies around the globe by zone.

From today’s date, get the first and last days of this current month. From each of those we ask for the previous or next occurrence of our desired day-of-week. We also accept that either that first or last of month may actually be the desired day-of-week which is what the “orSame” means in the TemporalAdjusters calls seen below.

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

LocalDate firstOfMonth = today.with( TemporalAdjusters.firstDayOfMonth() );
LocalDate monday = firstOfMonth.with( TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY ) );

LocalDate endOfMonth = today.with( TemporalAdjusters.lastDayOfMonth() );
LocalDate sunday = endOfMonth.with( TemporalAdjusters.nextOrSame( DayOfWeek.SUNDAY ) );

By the way, if you need to represent the entire month, look at the YearMonth class.

Upvotes: 3

Uriel Padiglione
Uriel Padiglione

Reputation: 1

You could use Calendar and make an iteration to find the days you're looking for like: Calendar.getInstance().get(Calendar.MONDAY) and Calendar.getInstance().get(Calendar.SUNDAY));

Upvotes: -1

Related Questions