How to format and display date in Java as '201904'

Java 8Object Oriented ProgrammingProgramming

To format and display date like this i.e. YearMonth, you need to set the pattern:

uuuuMM

At first, set a LocalDate:

LocalDate localDate = LocalDate.now();

Now format and display date as ‘201904’:

localDate.format(DateTimeFormatter.ofPattern("uuuuMM"))

Example

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Demo {
   public static void main(String[] args) {
      LocalDate localDate = LocalDate.now();
      System.out.println("Date = "+localDate);
      System.out.println("Date (Year and Month) = "+localDate.format(DateTimeFormatter.ofPattern("uuuuMM")));
   }
}

Output

Date = 2019-04-19
Date (Year and Month) = 201904
raja
Published on 25-Apr-2019 15:51:05
Advertisements