在java中实现日期类型和字符串类型的转换大全(Date String Timestamp Datetime)

用Timestamp来记录日期时间还是很方便的,但有时候显示的时候是不需要小数位后面的毫秒的,这样就需要在转换为String时重新定义格式。

Date、String、Timestamp之间的转换!

 

  1. public static void main(String[] args) {  
  2.    // TODO Auto-generated method stub  
  3. DateFormat format = new SimpleDateFormat("yyyy-MM-dd");           
  4. Date date = null;      
  5. String str = null;                    
  6.                
  7. // String转Date      
  8. str = "2009-01-06";            
  9. try {      
  10.    date = format.parse(str); // Wed sep 26 00:00:00 CST 2007      
  11. catch (ParseException e) {      
  12.    e.printStackTrace();      
  13. }                 
  14. date = java.sql.Date.valueOf(str); // 只保留日期部分,返回的是java.sql.Date 2007-9-26   
  15. System.out.println(date);  
  16.   
  17.   
  18.   
  19. // Date转String      
  20. date = new Date();   // Wed sep 26 18 17:14:01 CST 2007         
  21. str = format.format(date); // 2007-9-26      
  22. System.out.println(str);  
  23. format = DateFormat.getDateInstance(DateFormat.SHORT);      
  24. str = format.format(date); // 07-9-26  
  25. System.out.println(str);  
  26.               
  27. format = DateFormat.getDateInstance(DateFormat.MEDIUM);      
  28. str = format.format(date); // 2007-9-26     
  29. System.out.println(str);  
  30. format = DateFormat.getDateInstance(DateFormat.FULL);      
  31. str = format.format(date); // 2007年9月26日 星期三   
  32. System.out.println(str);  
  33. }  

 

Timestamp和String之间转换的函数:

  1. public static void main(String[] args) {  
  2.    // TODO Auto-generated method stub  
  3.    //Timestamp转化为String:  
  4.     SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//定义格式,不显示毫秒  
  5.     Timestamp now = new Timestamp(System.currentTimeMillis());//获取系统当前时间  
  6.     String str = df.format(now);  
  7.     System.out.println(str);  
  8.       
  9.   
  10.   
  11. ///String转化为Timestamp:  
  12. SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  13.     Date date = new Date();  
  14.     String time = df1.format(date);  
  15.     Timestamp ts = Timestamp.valueOf(time);  
  16.     System.out.println(ts);  
  17.   
  18. }  

 http://blog.csdn.net/cheung1021/article/details/6444043

原文地址:https://www.cnblogs.com/cmblogs/p/4402921.html