String转Date报错:Unparseable date: "20180608" ;

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"一致

你可能感兴趣的:(类型转换问题)