【Java】String和Date、Timestamp之间的转换

首先,定义一个Format的日期格式:

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

一、String与Date(java.util.Date)互转

【Java】String和Date、Timestamp之间的转换
 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);
【Java】String和Date、Timestamp之间的转换

二、String与Timestamp互转

【Java】String和Date、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         }
【Java】String和Date、Timestamp之间的转换

三、Date( java.util.Date )和Timestamp互转

【Java】String和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);
【Java】String和Date、Timestamp之间的转换

 

参考博客:http://yunnick.iteye.com/blog/1074495

【Java】String和Date、Timestamp之间的转换

上一篇:算法的时间复杂度的公式理解


下一篇:android 支持上拉加载,下拉刷新的列表控件SwipeRefreshLayout的二次封装