Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all possible years from the given day, day of the week, and month?

Tags:

date

math

formula

I want to get the set of years which pertain to a specific date, week of the day and month. There are possibilities that I can get various years from this pattern. Suppose Date is 15, Month is August and Week of the day is Tuesday then, How would I find the years that are valid? Is there a formula for this?

like image 983
mohsin Avatar asked Jul 10 '15 07:07

mohsin


1 Answers

Would this fully solve your problem?

The idea behind this:

  • Start from the specific date (August 15th) from year 0
  • if the date is on the specified weekday --> add it to your list
  • add 1 year
  • back to square 1

(till your specified MAX_DATE is reached)

List<Integer> validYears = new ArrayList<>();
    LocalDate date = LocalDate.of(0, Month.AUGUST, 15);
    while (date.getYear() < 2015) {
        if (date.getDayOfWeek() == DayOfWeek.TUESDAY) {
            validYears.add(date.getYear());
        }
        date = date.plusYears(1);
    }
    validYears.forEach(year -> System.out.println(year));

Edit: if your date is February 29th you should add following code (Because if you add 1 year to 0000-02-29 it will give you 0001-02-28, and from there on you will stay at the 28th)

if (date.isLeapYear()) { //And date was feb. 29
            date = date.withDayOfMonth(29);
        }

Heres a version with streams:

int day = 29;
Month month = Month.FEBRUARY;
List<LocalDate> collect = IntStream.range(0, 2016).filter(year -> day <= LocalDate.of(year, month, 1).lengthOfMonth())
            .mapToObj(year -> LocalDate.of(year, month, day)).filter(date -> date.getDayOfWeek() == DayOfWeek.TUESDAY)
            .collect(Collectors.toList());

collect.forEach((year -> System.out.println(year)));
like image 72
griFlo Avatar answered Sep 25 '22 00:09

griFlo