One, string and Date (java.util.Date) each other
1.1 String--Date
String datestr = "2010/05/04 12:34:23"; New Date (); // Note format is formatted to match the format of the date string New SimpleDateFormat ("Yyyy/mm/dd HH:mm:ss"); Try { = sdf.parse (datestr); System.out.println (Date.tostring ()); Catch (Exception e) { e.printstacktrace (); }
1.2 Date, String
date to string conversion, you can set any of the conversion formats format
String datestr = ""; Date Date=NewDate (); //format can be used in anyDateFormat SDF =NewSimpleDateFormat ("Yyyy/mm/dd HH:mm:ss"); DateFormat SDF2=NewSimpleDateFormat ("Yyyy-mm-dd hh/mm/ss"); Try{datestr=Sdf.format (date); System.out.println (DATESTR); Datestr=Sdf2.format (date); System.out.println (DATESTR); } Catch(Exception e) {e.printstacktrace (); }
Two, string and timestamp mutual transfer
2.1 String->timestamp
Using the timestamp valueof () method
New Timestamp (System.currenttimemillis ()); = "2011-05-09 11:49:45"; Try { = timestamp.valueof (tsstr); SYSTEM.OUT.PRINTLN (TS); Catch (Exception e) { e.printstacktrace (); }
Note: The type of string must be a yyyy-mm-dd hh:mm:ss[.f...] 这样的格式,中括号表示可选,否则报错!!!
shape such as:
If the string is in another format, consider re-parsing the string, and then reorganizing ~ ~
2.2 Timestamp, String
Use the ToString () method of timestamp or borrow DateFormat
Timestamp ts =NewTimestamp (System.currenttimemillis ()); String Tsstr= ""; DateFormat SDF=NewSimpleDateFormat ("Yyyy/mm/dd HH:mm:ss"); Try { //Method OneTsstr =Sdf.format (TS); System.out.println (TSSTR); //Method TwoTsstr =ts.tostring (); System.out.println (TSSTR); } Catch(Exception e) {e.printstacktrace (); }
It is easy to see that the advantage of method one is that it can be flexibly set in the form of strings.
Third, Date ( java.util.Date ) and timestamp mutual transfer
Disclaimer: The API indicates that date and Timesta are parent-child relationships
3.1 Timestamp-Date
New Timestamp (System.currenttimemillis ()); New Date (); Try { = ts; SYSTEM.OUT.PRINTLN (date); Catch (Exception e) { e.printstacktrace (); }
Very simple, but now the entity that the date object points to is a timestamp, that is, date has a method of the date class, but the execution entity of the overridden method is in timestamp.
3.2 Date, Timestamp
The parent class cannot be converted directly to the subclass, with the help of the intermediate string~~~~
Note: Use the following method to be more concise
Timestamp ts = new Timestamp (Date.gettime ());
string and date, timestamp