1. 程式人生 > >JAVA的String,Timestamp和Date資料型別之間的裝換

JAVA的String,Timestamp和Date資料型別之間的裝換

 

String  ==>  Date

 

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

String  ==>  Timestamp

 

 //String 轉化為Timestamp
        //valueOf(String str)
        try {
            String tsStr = "2018-10-16 11:49:45";
            Timestamp ts = Timestamp.valueOf(tsStr);
            System.out.println(ts);
        } catch (Exception e) {
            e.printStackTrace();
        }

 

Date  ==>  String

        //Date 轉化為String,通過SimpleDateFormat的format方法
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(new Date());
        System.out.println(format);

 

Date ==>  Timestamp

 

        //Date 轉化為Timestamp
        Date date = new Date();
        Timestamp timestamp = new Timestamp(date.getTime());
        System.out.println(timestamp);

 

Timestamp  ==>  Date

        //Timestamp 轉化為Date
        Timestamp timestam= new Timestamp(System.currentTimeMillis());
        Date d = timestam;
        System.out.println(d.toString() + "==="+d);

Timestamp  ==>  String

 

        //Timestamp 轉化為String
        Timestamp timesta = new Timestamp(System.currentTimeMillis());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = simpleDateFormat.format(timesta);
        System.out.println(format1);

 

 

SO,結果為: