Shock! Java date formatting pit!
•
Java
preface
Yyyy and YYYY
Sample code
@Test
public void testWeekBasedYear() {
Calendar calendar = Calendar.getInstance();
// 2019-12-31
calendar.set(2019,Calendar.DECEMBER,31);
Date strDate1 = calendar.getTime();
// 2020-01-01
calendar.set(2020,Calendar.JANUARY,1);
Date strDate2 = calendar.getTime();
// 大写 YYYY
SimpleDateFormat formatYYYY = new SimpleDateFormat("YYYY/MM/dd");
System.out.println("2019-12-31 转 YYYY/MM/dd 格式: " + formatYYYY.format(strDate1));
System.out.println("2020-01-01 转 YYYY/MM/dd 格式: " + formatYYYY.format(strDate2));
// 小写 YYYY
SimpleDateFormat formatyyyy = new SimpleDateFormat("yyyy/MM/dd");
System.out.println("2019-12-31 转 yyyy/MM/dd 格式: " + formatyyyy.format(strDate1));
System.out.println("2020-01-01 转 yyyy/MM/dd 格式: " + formatyyyy.format(strDate2));
}
Output results
2019-12-31 转 YYYY/MM/dd 格式: 2020/12/31
2020-01-01 转 YYYY/MM/dd 格式: 2020/01/01
2019-12-31 转 yyyy/MM/dd 格式: 2019/12/31
2020-01-01 转 yyyy/MM/dd 格式: 2020/01/01
How did yyyy do it
DD and DD
Sample code
private static void tryit(int Y,int M,int D,String pat) {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern(pat);
LocalDate dat = LocalDate.of(Y,M,D);
String str = fmt.format(dat);
System.out.printf("Y=%04d M=%02d D=%02d " +
"formatted with " +
"\"%s\" -> %s\n",Y,D,pat,str);
}
public static void main(String[] args){
tryit(2020,01,20,"MM/DD/YYYY");
tryit(2020,21,"DD/MM/YYYY");
tryit(2020,22,"YYYY-MM-DD");
tryit(2020,03,17,18,19,"YYYY-MM-DD");
}
Output results
Y=2020 M=01 D=20 formatted with "MM/DD/YYYY" -> 01/20/2020
Y=2020 M=01 D=21 formatted with "DD/MM/YYYY" -> 21/01/2020
Y=2020 M=01 D=22 formatted with "YYYY-MM-DD" -> 2020-01-22
Y=2020 M=03 D=17 formatted with "MM/DD/YYYY" -> 03/77/2020
Y=2020 M=03 D=18 formatted with "DD/MM/YYYY" -> 78/03/2020
Y=2020 M=03 D=19 formatted with "YYYY-MM-DD" -> 2020-03-79
conclusion
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码