Timestamp 的使用

java.sql.Timestamp的使用:

1、把String类型转换成Timestamp类型

  String datestr = "2015-07-08 11:32:21.451";

  Timestamp ts = Timestamp.valueOf(datestr);

  System.out.println(ts);

打印出:2015-07-08 11:32:21.451

把Timestamp类型转换成String类型

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

  Timestamp nowdate = new Timestamp(System.currentTimeMillis());

  String datestr = sdf.format(nowdate);

  System.out.println(datestr);

打印出:2015-07-08 11:32:21.45

2、获取当前时间

a、

Timestamp nowdate1 =new Timestamp(System.currentTimeMillis());

System.out.println("System.currentTimeMillis():" + nowdate1);

打印出:System.currentTimeMillis():2015-07-08 11:32:21.453

b、

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

System.out.println("new Date()" + nowdate2);

打印出:new date():2015-07-08 11:32:21.453

   注:String的类型必须形如: yyyy-mm-dd hh:mm:ss[.f...] 这样的格式,中括号表示可选

实例:

import java.sql.Timestamp; import java.text.SimpleDateFormat;

public class TimestampTest {

 public static void main(String[] args) {   

    //TimeStamp转换成String     

Timestamp ts = new Timestamp(System.currentTimeMillis());     

String tsStr = "";     

String tsStr2= "";     

String tsStr3="2014-07-08 21:17:58";     

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");           

try{      

//方法一,优势在于可以灵活的设置字符串的形式      

tsStr = sdf.format(ts);      

System.out.println(tsStr);      

//方法二      

tsStr2 =ts.toString();      

System.out.println(tsStr2);      

//方法三      

Timestamp s =Timestamp.valueOf(tsStr3);      

System.out.println(s);                       

}catch(Exception e )

{       e.printStackTrace();  

    }       }

打印出:

2015/07/08 21:21:56
2015-07-08 21:21:56.111
2014-07-08 21:17:58.0

}

原文地址:https://www.cnblogs.com/s1328/p/4630021.html