How to get only the dates where the last day of the month comes on Monday between two given dates

Viewed 72

The return value should be a string like "10/31/2016 8/31/2017". This function returns all Mondays of the year, but I just need the dates with the last Mondays of every month if they are the last day of the month.

function getMondays(startYear, endYear) {
  const startDate = new Date(startYear, 0, 2)
  const endDate = new Date(endYear, 11, 32)

  var i = startDate,
  month = i.getYear(),
  mondaysOfYear = []

  while (i.getDay() !== 2) {
  i.setDate(i.getDate() + 1)
  }

  while (i.getYear() === month) {
    mondaysOfYear.push(new Date(i.getTime()))
    i.setDate(i.getDate() + 7)
  }
  return mondaysOfYear
}
getMondays(2017, 2017)
5 Answers

Your Question is not clear, but apparently you want to find all occurrences where the last day of the month happens to be a Monday.

java.time

The modern approach uses the java.time classes. Specifically, the LocalDate class represents a date-only value without time-of-day and without time zone. Also the classes Year and YearMonth and DayOfWeek, as their name suggests.

Rather than pass mere integers, you can pass Year objects for type-safety, making your code more self-documenting.

Year startYear = Year.of( 2016 );
Year stopYear = Year.of( 2018 );

Define your utility method.

public List< LocalDate > calcMondays ( Year startYear , Year stopYear ) { … }

Pass that pair of objects.

List< LocalDate> dates = this.calcMondays( startYear , stopYear ) ;

I suggest consistent use of the Half-Open approach to defining a span-of-time. In this approach, the beginning is inclusive while the ending is exclusive. So a period of 2017-2019 would start on the first day of 2017 and run up to, but not include, the first day of 2019, for a period of 2 years.

Get the YearMonth of the start and stop, representing the month as a whole.

YearMonth startYm = YearMonth.from( startYear.atDay( 1 ) ) ;
YearMonth stopYm = YearMonth.from( stopYear.atDay( 1 ) ) ;

Define a collection of our found dates.

int initialCapacity = ( int ) ChronoUnit.MONTHS.between( startYear.atDay( 1 ) , stopYear.atDay( 1 ) );
List< LocalDate > lastMondays = new ArrayList<>( initialCapacity ) ;

Define the day-of-week we are targeting. Use DayOfWeek enum.

DayOfWeek dow = DayOfWeek.MONDAY ; 

Define a TemporalAdjuster, using an implementation found in TemporalAdjusters class.

TemporalAdjuster ta = TemporalAdjusters.lastInMonth( dow ) ;

Loop the months. For each, determine the first Monday. Use a TemporalAdjuster implementation found in the TemporalAdjusters class.

YearMonth ym = startYm ;
while( ym.isBefore( stopYm ) ) {
    LocalDate firstOfMonth = ym.atDay( 1 ) ;
    LocalDate ld = firstOfMonth.with( ta ) ;
    lastMondays.add( ld ) ;  // Collect our last-monday-of-this-month. 
    // Set up the next loop.
    ym = ym.plusMonths( 1 ) ;
}

Report.

System.out.println( lastMondays ) ;

See that code run live at IdeOne.com.

[2016-01-25, 2016-02-29, 2016-03-28, 2016-04-25, 2016-05-30, 2016-06-27, 2016-07-25, 2016-08-29, 2016-09-26, 2016-10-31, 2016-11-28, 2016-12-26, 2017-01-30, 2017-02-27, 2017-03-27, 2017-04-24, 2017-05-29, 2017-06-26, 2017-07-31, 2017-08-28, 2017-09-25, 2017-10-30, 2017-11-27, 2017-12-25]

Now let's modify that loop to focus on cases only where the last day of the month happens to be a Monday.

YearMonth ym = startYm;
while ( ym.isBefore( stopYm ) ) {
    LocalDate endOfMonth = ym.atEndOfMonth();
    if ( endOfMonth.getDayOfWeek().equals( dow ) ) {
        lastMondays.add( endOfMonth );  // Collect our last-monday-of-this-month.
    }
    // Set up the next loop.
    ym = ym.plusMonths( 1 );
}

See this code run live at IdeOne.com.

[2016-02-29, 2016-10-31, 2017-07-31]

Notice that these results differ from those given in the Question. I verified that these here are correct, and the Question’s results are incorrect.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Related