String轉Date報錯:Unparseable date: "20180608" ;
阿新 • • 發佈:2018-11-05
SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy/MM/dd"); // string轉date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); // string轉date Calendar now = Calendar.getInstance(); // 獲取當前系統時間 String nowYear = String.valueOf(now.get(Calendar.YEAR)); // 年 String nowMonth = StringUtils.leftPad(String.valueOf(now.get(Calendar.MONTH) + 1), 2, "0"); // 月 String nowDay = StringUtils.leftPad(String.valueOf(now.get(Calendar.DAY_OF_MONTH)), 2, "0"); // 日 Date nowDate = sdf.parse(nowYear + nowMonth + nowDay); // 20180608
這時候就會報錯Unparseable date: "20180608"。因為我string轉date時格式是"yyyy/MM/dd",而呼叫給的引數是"20180608",長度是不一致的,所以報錯。應該這樣寫最後一句
Date nowDate = sdf.parse(nowYear +"/"+ nowMonth +"/"+ nowDay);
總結:SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); 給的引數長度和格式一定要跟"yyyy/MM/dd"一致