经常我们会遇到时间戳Timestamp(java.sql.Timestamp)、字符串String(java.util.Date)、时间Date(java.util.Date)之间的相互转换,以下就总结一下这三类相互转换的写法。
一.String、Date之间的相互转换
1.String转换为Date:
String dateStr = "2010/05/04 12:34:23"; Date date = new Date(); //注意format的格式要与日期String的格式相匹配 DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); try { date = dateFormat.parse(dateStr); System.out.println(date.toString()); } catch (Exception e) { e.printStackTrace(); }
2.Date转换为String:
String dateStr = ""; Date date = new Date(); //日期向字符串转换,可以设置任意的转换格式format DateFormat format1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); DateFormat format2 = new SimpleDateFormat("MM-dd hh"); //HH返回的是24小时制的时间;hh返回的是12小时制的时间 try { dateStr = format1.format(date); System.out.println(dateStr); dateStr = format2.format(date); System.out.println(dateStr); } catch (Exception e) { e.printStackTrace(); }
二.String与Timestamp之间的相互转换
1.String转换为TimeStamp(使用Timestamp的valueOf()方法)
Timestamp timestamp = new Timestamp(System.currentTimeMillis()); String tsStr = "2011-05-09 11:49:45"; try { timestamp = Timestamp.valueOf(tsStr); System.out.println(timestamp); } catch (Exception e) { e.printStackTrace();
}
注:String的类型必须形如: yyyy-mm-dd hh:mm:ss[.f...] 这样的格式,中括号表示可选,否则报错。
如果String为其他格式,可考虑重新解析下字符串,再重组。
2.TimeStamp转换为String(使用Timestamp的toString()方法或者借用DateFormat)
Timestamp timestamp = new Timestamp(System.currentTimeMillis()); String string = ""; DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); try { //方法一 string = format.format(timestamp); System.out.println(string); //方法二 string = timestamp.toString(); System.out.println(string); } catch (Exception e) { e.printStackTrace(); }
方法一的优势在于可以灵活的设置字符串的形式。
三.Date和Timestamp的相互转换(Date和Timestamp是父子类关系)
1.TimeStamp转换为Date
Timestamp timestamp = new Timestamp(System.currentTimeMillis()); Date date = new Date(); try { date = timestamp; System.out.println(date); } catch (Exception e) { e.printStackTrace(); }
注意:但是此刻date对象指向的实体却是一个Timestamp,即date拥有Date类的方法,但被覆盖的方法的执行实体在Timestamp中。
2.Date转换为TimeStamp
父类不能直接向子类转化,可借助中间的String。
注:使用以下方式更简洁
Timestamp ts = new Timestamp(date.getTime());
Stay hungry,stay foolish !