java字符串类型和时间类型的转换
类型转换
//reqeust.getParameter获取字符串直接赋值
1 public static Date date(String date_str) { 2 try { 3 Calendar zcal = Calendar.getInstance();//日期类 4 Timestamp timestampnow = new Timestamp(zcal.getTimeInMillis());//转换成正常的日期格式 5 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");//改为需要的东西 6 ParsePosition pos = new ParsePosition(0); 7 java.util.Date current = formatter.parse(date_str, pos); 8 timestampnow = new Timestamp(current.getTime()); 9 return timestampnow; 10 } 11 catch (NullPointerException e) { 12 return null; 13 } 14 }
1 //Date类型转换成String类型 2 public static String toJson(Object obj){ 3 String reuqest=null; 4 //对象映射 5 ObjectMapper mapper=new ObjectMapper(); 6 //设置时间格式 7 SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy年MM月dd日"); 8 mapper.setDateFormat(dateFormat); 9 try { 10 reuqest=mapper.writeValueAsString(obj); 11 } catch (JsonProcessingException e) { 12 // TODO Auto-generated catch block 13 e.printStackTrace(); 14 } 15 return reuqest; 16 }
//String类型转换成Date类型
1 public static Date date(String date_str) {
2 try { 3 Calendar zcal = Calendar.getInstance();//日期类 4 Timestamp timestampnow = new Timestamp(zcal.getTimeInMillis());//转换成正常的日期格式 5 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");//改为需要的东西 6 ParsePosition pos = new ParsePosition(0); 7 java.util.Date current = formatter.parse(date_str, pos); 8 timestampnow = new Timestamp(current.getTime()); 9 return timestampnow; 10 } 11 catch (NullPointerException e) { 12 return null; 13 } 14 }