Java TemporalAdjuster implement to adjust date

Description

Java TemporalAdjuster implement to adjust date

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.Year;
import java.time.format.DateTimeFormatter;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;

class PaydayAdjuster implements TemporalAdjuster {
  public Temporal adjustInto(Temporal input) {
    LocalDate date = LocalDate.from(input);
    int day;//from  w w w  . ja  va 2  s  . com
    if (date.getDayOfMonth() < 15) {
      day = 15;
    } else {
      day = date.with(TemporalAdjusters.lastDayOfMonth()).getDayOfMonth();
    }
    date = date.withDayOfMonth(day);
    if (date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY) {
      date = date.with(TemporalAdjusters.previous(DayOfWeek.FRIDAY));
    }

    return input.with(date);
  }
}

public class Main {

  public static void main(String[] args) {
    Month month = Month.APRIL;

    DateTimeFormatter format;

    LocalDate date = Year.now().atMonth(month).atDay(12);
    LocalDate nextPayday = date.with(new PaydayAdjuster());

    format = DateTimeFormatter.ofPattern("yyyy MMM d");
    String out = date.format(format);
    System.out.printf("Given the date:  %s%n", out);
    out = nextPayday.format(format);
    System.out.printf("the next payday: %s%n", out);

  }
}



PreviousNext

Related