Java Data Type How to - Format Year Month as '201506'








Question

We would like to know how to format Year Month as '201506'.

Answer

import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
/*from  www.ja  va2 s . c om*/
public class Main {

  public static void main(String[] args) {

    System.out.println(toUUUUMM(YearMonth.now()));
  }

  public static String toUUUUMM(YearMonth yearAndMonth) {
    return yearAndMonth.format(DateTimeFormatter.ofPattern("uuuuMM"));
  }
}

The code above generates the following result.