要像这样格式化和显示日期,例如YearMonth,您需要设置模式:
uuuuMM
首先,设置一个LocalDate:
LocalDate localDate = LocalDate.now();
现在格式化并显示日期为'201904':
localDate.format(DateTimeFormatter.ofPattern("uuuuMM"))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")));
}
}输出结果
Date = 2019-04-19 Date (Year and Month) = 201904