首先,定义一个Format的日期格式:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
一、String与Date(java.util.Date)互转
1 // String ---> Date 2 String sinceTime = "2014-01-26 14:34:14"; 3 Date date = new Date(); 4 System.out.println("date = " + date); 5 try { 6 date = df.parse(sinceTime); // 将sinceTime转为date类型 7 } catch (ParseException e) { 8 System.out.println("sinceTime = " + sinceTime); 9 } 10 System.out.println("date format = " + date); 11 System.out.println("date to long = " + date.getTime()); 12 13 // Date ---> String 14 String dateStr = ""; 15 dateStr = df.format(date); 16 System.out.println("date String = " + dateStr);
二、String与Timestamp互转
1 // String ---> Timestamp 2 Timestamp ts = new Timestamp(System.currentTimeMillis()); 3 String timeStr = "2014-01-26 14:34:14"; 4 ts = Timestamp.valueOf(timeStr); 5 System.out.println("timestamp = " + ts); 6 7 // Timestamp ---> String 8 String tsStr = ""; 9 try { 10 // 方法一 11 tsStr = df.format(ts); 12 System.out.println("Timestamp -> String " + tsStr); 13 // 方法二 14 tsStr = ts.toString(); 15 System.out.println("Timestamp -> String " + tsStr); 16 } catch (Exception e) { 17 e.printStackTrace(); 18 }
三、Date( java.util.Date )和Timestamp互转
1 // Timestamp ---> Date 2 try { 3 date = ts; 4 System.out.println("Timestamp -> Date " + date); 5 } catch (Exception e) { 6 e.printStackTrace(); 7 } 8 9 // Date ---> Timestamp 10 Timestamp ts2 = new Timestamp(date.getTime()); 11 System.out.println("Date -> Timestamp " + ts2);
参考博客:http://yunnick.iteye.com/blog/1074495