字符串和date之间的相互转换方法


 

 1     /**
 2      * 字符串转Date方法
 3      * @param dateStr
 4      * @param format 如yyyy-MM-dd HH:mm:ss等
 5      * @return
 6      * @throws Exception
 7      */
 8     public static Date stringToDate(String dateStr,String format) throws Exception{
 9         if(dateStr==null||"".equals(dateStr)){
10             throw new Exception("stringToDate:要转换的日期参数为空!");
11         }
12         Date date = null;
13         try{
14             SimpleDateFormat sdf = new SimpleDateFormat(format);
15             date = sdf.parse(dateStr);
16         }catch(Exception e){
17             e.printStackTrace();
18         }
19 
20         return date;
21     }
22     /**
23      * Date转字符串方法
24      * @param date
25      * @param format 如yyyy-MM-dd HH:mm:ss等
26      * @return
27      * @throws Exception
28      */
29     public static String dateToString(Date date,String format) throws Exception{
30         if(date==null){
31             throw new Exception("dateToString:要转换的日期参数为空!");
32         }
33         String dateStr = "";
34         try{
35             SimpleDateFormat sdf = new SimpleDateFormat(format);
36             dateStr = sdf.format(date);
37         }catch(Exception e){
38             e.printStackTrace();
39         }
40 
41         return dateStr;
42     }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM