字符串:String aa="物品日报表 2018年9月29日";
Date newdate=stringZhuanDate(aa);
//字符串里的时间转换成date public Date stringZhuanDate(String biaoti){ String riqi=null; String nian=splitData(biaoti,"表","年").trim(); System.out.println("获取字符串里的年=="+nian); String yue=splitData(biaoti,"年","月").trim(); System.out.println("获取字符串里的月=="+yue); String ri=splitData(biaoti,"月","日").trim(); System.out.println("获取字符串里的日=="+ri); if(yue.length()<2){ yue="0"+yue; } if(ri.length()<2){ ri="0"+ri; } riqi=nian+"-"+yue+"-"+ri; System.out.println("拼装=="+riqi); Date date = null; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { // 注意格式需要与上面一致,不然会出现异常 date = sdf.parse(riqi); } catch (ParseException e) { e.printStackTrace(); } System.out.println("字符串转换成时间:" + date); return date; }
// 截取2个指定字符之间的字符串 public String splitData(String str, String strStart, String strEnd) { String tempStr; tempStr = str.substring(str.indexOf(strStart) + 1, str.lastIndexOf(strEnd)); return tempStr; }