Search code examples
javadatetimelocaldate

Formatting LocalDate in Java


I defined the following format in Java :

//define format of YYYYMMDD
private final DateTimeFormatter dtf = DateTimeFormatter.BASIC_ISO_DATE;

My application fetches a certain date from the calendar:

LocalDate localDate = fetchDate(); // fetch date in format "yyyy-mm-dd"

I want to store an additional two dates in format of dtf. The startOfMonth and endOfMonth of the given localDate.

E.g. if localDate is "2019-12-12" I want to create the following two variables -

String startOfMonth = "20191201";
String endOfMonth = "20191231";

How can I do that?


Solution

  • LocalDate atStartOfMonth = localDate.with(TemporalAdjusters.firstDayOfMonth());
    LocalDate atEndOfMonth = localDate.with(TemporalAdjusters.lastDayOfMonth());
    

    And then you format those local dates the way you want to (i.e. with your dtf formatter)