Java:String和Date、Timestamp之間的轉換


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

1.1 String -> Date

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();
        }
View Code

  1.2 Date -> String

日期向字符串轉換,可以設置任意的轉換格式format

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();
        }
View Code

 二、String與Timestamp互轉

2.1 String ->Timestamp

使用Timestamp的valueOf()方法

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();
        }
View Code

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

如果String為其他格式,可考慮重新解析下字符串,再重組~~ 

2.2 Timestamp -> String 

使用Timestamp的toString()方法或者借用DateFormat

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();
        }
View Code

 很容易能夠看出來,方法一的優勢在於可以靈活的設置字符串的形式。

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

聲明:查API可知,Date和Timesta是父子類關系 

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();
        }
View Code

很簡單,但是此刻date對象指向的實體卻是一個Timestamp,即date擁有Date類的方法,但被覆蓋的方法的執行實體在Timestamp中。

 

 

3.2 Date -> Timestamp

 

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

注:使用以下方式更簡潔

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM