1、将一个字符串日期转换成日期格式
1 /** 2 * 将一个字符串日期转换成日期格式 3 * @param date 4 * @param pattern 5 * @return 6 */ 7 public static Date toDate(String date, String pattern) { 8 if (("" + date).equals("")) { 9 return null; 10 } 11 if (pattern == null) { 12 pattern = "yyyy-MM-dd"; 13 } 14 SimpleDateFormat sdf = new SimpleDateFormat(pattern); 15 Date newDate = new Date(); 16 try { 17 newDate = sdf.parse(date); 18 } catch (Exception ex) { 19 ex.printStackTrace(); 20 } 21 return newDate; 22 }
2、把日期转换成字符串型
1 /** 2 * 把日期转换成字符串型 3 * @param date 4 * @param pattern 5 * @return 6 */ 7 public static String toString(Date date, String pattern) { 8 if (date == null) { 9 return ""; 10 } 11 if (pattern == null) { 12 pattern = "yyyy-MM-dd"; 13 } 14 String dateString = ""; 15 SimpleDateFormat sdf = new SimpleDateFormat(pattern); 16 try { 17 dateString = sdf.format(date); 18 } catch (Exception ex) { 19 ex.printStackTrace(); 20 } 21 return dateString; 22 }
3、计算两个日期之间相差的天数
1 /** 2 * 计算两个日期之间相差的天数 3 * @param date1 4 * @param date2 5 * @return 6 */ 7 public static int daysBetween(Date smdate,Date bdate) { 8 long between_days = 0; 9 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 10 try { 11 smdate = sdf.parse(sdf.format(smdate)); 12 bdate = sdf.parse(sdf.format(bdate)); 13 Calendar cal = Calendar.getInstance(); 14 cal.setTime(smdate); 15 long time1 = cal.getTimeInMillis(); 16 cal.setTime(bdate); 17 long time2 = cal.getTimeInMillis(); 18 between_days=(time2-time1)/(1000*3600*24); 19 } catch (ParseException e) { 21 e.printStackTrace(); 22 } 23 return Integer.parseInt(String.valueOf(between_days)); 24 }