1. 程式人生 > >[java]String和Date、Timestamp之間的轉換

[java]String和Date、Timestamp之間的轉換

方式 父類 print 關系 否則 get pre rac pri

一、String與Date(java.util.Date)互轉

1.1 String -> Date

Date date = DateFormat.parse(String str);

String dateStr = "2010/05/04 12:34:23";  
Date date = new Date();  
//註意format的格式要與日期String的格式相匹配  
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");  
try {  
     date = sdf.parse(dateStr);  
     System.out.println(date.toString());  
} 
catch (Exception e) { e.printStackTrace(); }

1.2 Date -> String

String str = DateFormat.format(Date date);

        String dateStr = "";  
        Date date = new Date();  
        //format的格式可以任意  
        DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");  
        DateFormat sdf2 
= new SimpleDateFormat("yyyy-MM-dd HH/mm/ss"); try { dateStr = sdf.format(date); System.out.println(dateStr); dateStr = sdf2.format(date); System.out.println(dateStr); } catch (Exception e) { e.printStackTrace(); }

二、String與Timestamp互轉

2.1 String ->Timestamp

Timestamp ts = Timestamp.valueOf(String str);

        Timestamp ts = new Timestamp(System.currentTimeMillis());  
        String tsStr = "2011-05-09 11:49:45";  
        try {  
            ts = Timestamp.valueOf(tsStr);  
            System.out.println(ts);  
        } catch (Exception e) {  
            e.printStackTrace();  
        } 

註:String的類型必須形如: yyyy-mm-dd hh:mm:ss[.f...] 這樣的格式,中括號表示可選,否則報錯

2.2 Timestamp -> String

方法1:String str = DateFormat.format(Timestamp ts);

方法2:String str = Timestamp.toString();

        Timestamp ts = new Timestamp(System.currentTimeMillis());  
        String tsStr = "";  
        DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");  
        try {  
            //方法一  
            tsStr = sdf.format(ts);  
            System.out.println(tsStr);  
            //方法二  
            tsStr = ts.toString();  
            System.out.println(tsStr);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }

三、Date( java.util.Date )和Timestamp互轉

Date和Timestamp是父子類關系

3.1 Timestamp(子類) -> Date(父類)

        Timestamp ts = new Timestamp(System.currentTimeMillis());  
        Date date = new Date();  
        try {  
            date = ts;  
            System.out.println(date);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  

3.2 Date -> Timestamp

父類不能直接向子類轉化,可借助中間的String。

註:使用以下方式更簡潔

Timestamp ts = new Timestamp(date.getTime());

轉自:https://www.cnblogs.com/mybloging/p/8067698.html

[java]String和Date、Timestamp之間的轉換