Java中时间格式 yyyyMMdd和yyyy-MM-dd相互转换

时间:2025-03-11 18:11:54
@Test public void dateConvertion() { String str = "20200201"; // String string = "2020-02-01"; //yyyy-MM-dd try { // yyyyMMdd转yyyy-MM-dd Date format1 = new SimpleDateFormat("yyyyMMdd").parse(str); String longDate = new SimpleDateFormat("yyyy-MM-dd").format(format1); System.out.println("yyyyMMdd转yyyy-MM-dd:"+longDate); // yyyy-MM-dd转yyyyMMdd Date format2 = new SimpleDateFormat("yyyy-MM-dd").parse(string); String shortDate = new SimpleDateFormat("yyyyMMdd").format(format2); System.out.println("yyyy-MM-dd转yyyyMMdd:"+shortDate); } catch (ParseException e) { throw new BizException("转换异常"); } }