PublicClassdatetest {/** Two common types of date formats * YYYY-MM-DD * YYYY/MM/DD*/PublicStaticvoid Main (string[] args)Throwsparseexception {//01.Date Convert to String Date date=NewDate (); SYSTEM.OUT.PRINTLN (date);//Use date conversion class SimpleDateFormat format=New SimpleDateFormat ("yyyy-mm-dd HH:MM:SS");//Convert dates to StringsSystem.out.println (Format.format (date));//02. String converted to Date string str= "2016-11-12 03:58:32"; Date=Format.parse (str); SYSTEM.OUT.PRINTLN (date); }//03. Convert SQL date to Util date@TestPublicvoidTest01 () {Date date=New Date ();//Java.util System.out.println (Date.getyear () +1900);//Java.sql.Date (Date) requires us to pass a long type of argument java.sql.Date sqldate=NewJava.sql.Date (Date.gettime ()); System.out.println (sqldate); System.out.println (Sqldate.getyear ()); }//04. Convert String to timestamp type (timestamp)@TestPublicvoidtest02 () {//Requires a long type parameter Timestamp ts=NewTimestamp (System.currenttimemillis ()); SYSTEM.OUT.PRINTLN (TS);//2016-11-12 16:11:27.828 String str= "2015-09-01 01:01:01";/** ValueOf (type of string must be the underlying) * Underlying code: [] Represents dispensable * String formaterror = "Timestamp format must be YYYY-MM-DD HH:MM:SS[.FFFFFFF FF] ";*/ts=Ts.valueof (str); SYSTEM.OUT.PRINTLN (TS); }//04. Convert the timestamp type to a string@TestPublicvoidtest03 () {Timestamp ts=NewTimestamp (System.currenttimemillis ());//01. The simplest waySystem.out.println (Ts.tostring ());//02.SimpleDateFormat DateFormat format=New SimpleDateFormat ("Yyyy/mm/dd hh:mm:ss"); System.out.println (Format.format (TS)); }/** 05. Convert the timestamp type to util. Date * * Underlying code Discovery Timestamp is a subclass of date * public class Timestamp extends Java.util.Date*/@TestPublicvoidtest04 () {Timestamp ts=NewTimestamp (System.currenttimemillis ()); Date date=NewDate (); System.out.println ("date====>" +Date); Date=ts;//Convert System.out.println ("ts=====>" +Date); }//06.util. Date cannot be converted directly to the timestamp type by using the string@TestPublicvoidtest05 () {Timestamp ts=NewTimestamp (System.currenttimemillis ()); Date date=NewDate (); System.out.println ("date====>" +Date);if (TSinstanceofDate) {ts= (Timestamp) date; // conversion } System.out.println ("ts=====>" +ts);}}
Java Date Conversion