一、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();
- }
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();
- }
二、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();
- }
注: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();
- }
很轻易可以或许看出来,办法一的上风在于可以灵活的设置字符串的情势。
三、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();
- }
很简单,然则此刻date对象指向的实体倒是一个Timestamp,即date拥有Date类的办法,但被覆盖的办法的履行实体在Timestamp中。
3.2 Date -> Timestamp
父类不克不及直接向子类转化,可借助中心的String~~~~
注:应用以式格式更简洁
Timestamp ts = new Timestamp(date.getTime());