date日期类型与String类型的相互转化

来源:互联网 发布:淘宝延长收款怎么取消 编辑:程序博客网 时间:2024/05/21 22:37
Code:
  1. import java.text.ParseException;  
  2. import java.text.SimpleDateFormat;  
  3. import java.util.Date;  
  4.   
  5. import org.apache.log4j.Logger;  
  6.   
  7. import com.fourstar.log4j.HelloLog4j;  
  8.   
  9. public class DateUtil {  
  10.     private static final Logger log = Logger.getLogger(HelloLog4j.class);//获得当前类      
  11.     public static Date toDate(String dateStr) {  
  12.         Date date = null;  
  13.         SimpleDateFormat formater = new SimpleDateFormat();  
  14.         formater.applyPattern("yyyy-MM-dd hh:m:ss");  
  15.         try {  
  16.             date = formater.parse(dateStr);  
  17.         } catch (ParseException e) {  
  18.             e.printStackTrace();  
  19.         }  
  20.         return date;  
  21.   
  22.     }  
  23.   
  24.     public static Date toDate(String dateStr, String f) {  
  25.         Date date = null;  
  26.         SimpleDateFormat formater = new SimpleDateFormat();  
  27.         formater.applyPattern(f);  
  28.         try {  
  29.             date = formater.parse(dateStr);  
  30.         } catch (ParseException e) {  
  31.             e.printStackTrace();  
  32.         }  
  33.         return date;  
  34.   
  35.     }  
  36.   
  37.     public static String toString(Date date) {  
  38.   
  39.         String time;  
  40.         SimpleDateFormat formater = new SimpleDateFormat();  
  41.   
  42.         formater.applyPattern("yyyy-MM-dd hh:m:ss");  
  43.         time = formater.format(date);  
  44.   
  45.         return time;  
  46.     }  
  47.   
  48.     public static String toString(Date date, String f) {  
  49.         String time;  
  50.         SimpleDateFormat formater = new SimpleDateFormat();  
  51.         formater.applyPattern(f);  
  52.         time = formater.format(date);  
  53.         return time;  
  54.     }  
  55.   
  56.     public static void main(String[] args) {  
  57.         Date todayDate = new Date();//date类型  
  58.         System.out.println(todayDate);  
  59.         String t = DateUtil.toString(todayDate,"yyyy-MM-dd hh:m:ss");//string类型  
  60.         System.out.println(t);  
  61.         todayDate = DateUtil.toDate(t, "yyyy-MM-dd hh:m:ss");//date类型  
  62.         System.out.println(todayDate);  
  63.     }  
  64.   
  65. }  
原创粉丝点击