One, string and Date (java.util.Date) each other
1.1 String--Date
Java code
- String datestr = "2010/05/04 12:34:23";
- Date date = new Date ();
- //Note format is formatted to match the format of the date string
- DateFormat SDF = new SimpleDateFormat ("Yyyy/mm/dd HH:mm:ss");
- try {
- Date = 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
Java code
- String datestr = "";
- Date date = new Date ();
- the//format format can be arbitrarily
- DateFormat SDF = new SimpleDateFormat ("Yyyy/mm/dd HH:mm:ss");
- DateFormat SDF2 = new SimpleDateFormat ("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
Java code
- Timestamp ts = new Timestamp (System.currenttimemillis ());
- String tsstr = "2011-05-09 11:49:45";
- try {
- ts = 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
Java code
- Timestamp ts = new Timestamp (System.currenttimemillis ());
- String tsstr = "";
- DateFormat SDF = new SimpleDateFormat ("Yyyy/mm/dd HH:mm:ss");
- try {
- //Method one
- TSSTR = Sdf.format (ts);
- System.out.println (TSSTR);
- //Method two
- Tsstr = 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
Java code
- timestamp ts = new timestamp ( System.currenttimemillis ());
- date date = new date ();
- try {
- date = 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 ());
Conversion between java:string and date, timestamp