1 PackageTest;2 3 ImportJava.sql.Timestamp;4 ImportJava.text.DateFormat;5 ImportJava.text.SimpleDateFormat;6 Importjava.util.Date;7 8 Public classTest1 {9 Public Static voidMain (string[] args) {TenTest1 t1=NewTest1 (); One T1.action1 (); A T1.action2 (); - T1.action3 (); - T1.action4 (); the t1.action5 (); - t1.action6 (); - - } + - //String-Date + Public voidAction1 () { AString datestr = "2010/05/04 12:34:23"; atDate Date =NewDate (); - //Note format is formatted to match the format of the date string -DateFormat SDF =NewSimpleDateFormat ("Yyyy/mm/dd HH:mm:ss"); - Try { -Date =Sdf.parse (DATESTR); - System.out.println (date.tostring ()); in}Catch(Exception e) { - e.printstacktrace (); to } + } - //Date , string date to string conversion, you can set any of the conversion formats format the Public voidAction2 () { *String datestr = ""; $Date Date =NewDate ();Panax Notoginseng //format can be used in any -DateFormat SDF =NewSimpleDateFormat ("Yyyy/mm/dd HH:mm:ss"); theDateFormat SDF2 =NewSimpleDateFormat ("Yyyy-mm-dd hh/mm/ss"); + Try { ADatestr =Sdf.format (date); the System.out.println (DATESTR); +Datestr =Sdf2.format (date); - System.out.println (DATESTR); $}Catch(Exception e) { $ e.printstacktrace (); - } - } the - //string->timestamp Note: The type of string must be shaped like: yyyy-mm-dd hh:mm:ss[.f ...] Such a format, the brackets indicate optional, otherwise error!!! Wuyi Public voidAction3 () { theTimestamp ts =NewTimestamp (System.currenttimemillis ()); -String tsstr = "2011-05-09 11:49:45"; Wu Try { -TS =timestamp.valueof (TSSTR); About System.out.println (TS); $}Catch(Exception e) { - e.printstacktrace (); - } - } A + //Timestamp String Use the ToString () method of Timestamp or borrow DateFormat the Public voidAction4 () { -Timestamp ts =NewTimestamp (System.currenttimemillis ()); $String tsstr = ""; theDateFormat SDF =NewSimpleDateFormat ("Yyyy/mm/dd HH:mm:ss"); the Try { the //Method One theTsstr =Sdf.format (TS); - System.out.println (TSSTR); in //Method Two theTsstr =ts.tostring (); the System.out.println (TSSTR); About}Catch(Exception e) { the e.printstacktrace (); the } the } + //Timestamp-Date - Public voidaction5 () { theTimestamp ts =NewTimestamp (System.currenttimemillis ());BayiDate Date =NewDate (); the Try { theDate =ts; - System.out.println (date); -}Catch(Exception e) { the e.printstacktrace (); the } the } the //Date-Timestamp - Public voidAction6 () { theDate time =NewDate (); theTimestamp DateTime =NewTimestamp (Time.gettime ()); the System.out.println (dateTime);94 } the}
Conversion between java:string and date, timestamp