Java Data Type How to - Get the next or same closest date from the specified days in daysOfWeek List at specified hour and min








Question

We would like to know how to get the next or same closest date from the specified days in daysOfWeek List at specified hour and min.

Answer

   /*from ww w  . jav  a2  s.com*/
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Main {
  public static void main(String[] argv) {
    DayOfWeek d = DayOfWeek.FRIDAY;
    List<DayOfWeek> l = new ArrayList<>();
    l.add(d);
    
    System.out.println(getNextClosestDateTime(l,22,20));
  }

  /**
   * Gets the next or same closest date from the specified days in
   * {@code daysOfWeek List} at specified {@code hour} and {@code min}.
   * 
   * @param daysOfWeek
   *          the days of week
   * @param hour
   *          the hour
   * @param min
   *          the min
   * @return the next or same date from the days of week at specified time
   * @throws IllegalArgumentException
   *           if the {@code daysOfWeek List} is empty.
   */
  public static LocalDateTime getNextClosestDateTime(
      List<DayOfWeek> daysOfWeek, int hour, int min)
      throws IllegalArgumentException {
    if (daysOfWeek.isEmpty()) {
      throw new IllegalArgumentException("daysOfWeek should not be empty.");
    }

    final LocalDateTime dateNow = LocalDateTime.now();
    final LocalDateTime dateNowWithDifferentTime = dateNow.withHour(hour)
        .withMinute(min).withSecond(0);

    // @formatter:off
    return daysOfWeek
        .stream()
        .map(
            d -> dateNowWithDifferentTime.with(TemporalAdjusters.nextOrSame(d)))
        .filter(d -> d.isAfter(dateNow))
        .min(Comparator.naturalOrder())
        .orElse(
            dateNowWithDifferentTime.with(TemporalAdjusters.next(daysOfWeek
                .get(0))));
    // @formatter:on
  }
}

/*
 * Copyright (C) 2004-2015 L2J Server
 * 
 * This file is part of L2J Server.
 * 
 * L2J Server is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * L2J Server is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

The code above generates the following result.