Java:String和Date、Timestamp之间的转换
1 package Test; 2 3 import java.sql.Timestamp; 4 import java.text.DateFormat; 5 import java.text.SimpleDateFormat; 6 import java.util.Date; 7 8 public class Test1 { 9 public static void main(String[] args) { 10 Test1 t1=new Test1(); 11 t1.action1(); 12 t1.action2(); 13 t1.action3(); 14 t1.action4(); 15 t1.action5(); 16 t1.action6(); 17 18 } 19 20 // String -> Date 21 public void action1(){ 22 String dateStr = "2010/05/04 12:34:23"; 23 Date date = new Date(); 24 //注意format的格式要与日期String的格式相匹配 25 DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 26 try { 27 date = sdf.parse(dateStr); 28 System.out.println(date.toString()); 29 } catch (Exception e) { 30 e.printStackTrace(); 31 } 32 } 33 // Date -> String 日期向字符串转换,可以设置任意的转换格式format 34 public void action2(){ 35 String dateStr = ""; 36 Date date = new Date(); 37 //format的格式可以任意 38 DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 39 DateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH/mm/ss"); 40 try { 41 dateStr = sdf.format(date); 42 System.out.println(dateStr); 43 dateStr = sdf2.format(date); 44 System.out.println(dateStr); 45 } catch (Exception e) { 46 e.printStackTrace(); 47 } 48 } 49 50 // String ->Timestamp 注:String的类型必须形如: yyyy-mm-dd hh:mm:ss[.f...] 这样的格式,中括号表示可选,否则报错!!! 51 public void action3(){ 52 Timestamp ts = new Timestamp(System.currentTimeMillis()); 53 String tsStr = "2011-05-09 11:49:45"; 54 try { 55 ts = Timestamp.valueOf(tsStr); 56 System.out.println(ts); 57 } catch (Exception e) { 58 e.printStackTrace(); 59 } 60 } 61 62 // Timestamp -> String 使用Timestamp的toString()方法或者借用DateFormat 63 public void action4(){ 64 Timestamp ts = new Timestamp(System.currentTimeMillis()); 65 String tsStr = ""; 66 DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 67 try { 68 //方法一 69 tsStr = sdf.format(ts); 70 System.out.println(tsStr); 71 //方法二 72 tsStr = ts.toString(); 73 System.out.println(tsStr); 74 } catch (Exception e) { 75 e.printStackTrace(); 76 } 77 } 78 // Timestamp -> Date 79 public void action5(){ 80 Timestamp ts = new Timestamp(System.currentTimeMillis()); 81 Date date = new Date(); 82 try { 83 date = ts; 84 System.out.println(date); 85 } catch (Exception e) { 86 e.printStackTrace(); 87 } 88 } 89 // Date -> Timestamp 90 public void action6(){ 91 Date time = new Date(); 92 Timestamp dateTime = new Timestamp(time.getTime()); 93 System.out.println(dateTime); 94 } 95 }