Public classDatetest {/** There are only two types of date formats * YYYY-MM-DD * YYYY/MM/DD*/ Public Static voidMain (string[] args)throwsParseException {//01.Date Convert to StringDate date=NewDate (); SYSTEM.OUT.PRINTLN (date); //using the date conversion classSimpleDateFormat format=NewSimpleDateFormat ("yyyy-mm-dd HH:MM:SS"); //convert dates to StringsSystem.out.println (Format.format (date)); //02. String converted to DateString str= "2016-11-12 03:58:32"; Date=format.parse (str); SYSTEM.OUT.PRINTLN (date); } //03. Convert SQL date to util date@Test Public voidtest01 () {Date Date=NewDate ();//java.util System.out.println (date.getyear () +1900); //java.sql.Date (Date) requires us to pass a long type of argumentJava.sql.Date sqldate=Newjava.sql.Date (Date.gettime ()); System.out.println (sqldate); System.out.println (Sqldate.getyear ()); } //04. Convert String to timestamp type (timestamp)@Test Public voidtest02 () {//requires a long type parameterTimestamp ts=NewTimestamp (System.currenttimemillis ()); SYSTEM.OUT.PRINTLN (TS); //2016-11-12 16:11:27.828String str= "2015-09-01 01:01:01"; /** VALUEOF (the type of the string must be the underlying) * The underlying code: [] Represents the dispensable * string formaterror = "Timestamp format must Be yyyy-mm-dd hh:mm:ss[.fffffffff] "; */TS=ts.valueof (str); SYSTEM.OUT.PRINTLN (TS); } //04. Convert the timestamp type to a string@Test Public voidtest03 () {Timestamp TS=NewTimestamp (System.currenttimemillis ()); //01. The simplest waySystem.out.println (ts.tostring ()); //02.SimpleDateFormatDateFormat format=NewSimpleDateFormat ("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*/@Test Public voidtest04 () {Timestamp TS=NewTimestamp (System.currenttimemillis ()); Date Date=NewDate (); System.out.println ("Date====>" +date); Date=ts;//ConversionSystem.out.println ("ts=====>" +date); } //06.util. Date cannot be converted directly to the timestamp type by using the string@Test Public voidtest05 () {Timestamp TS=NewTimestamp (System.currenttimemillis ()); Date Date=NewDate (); System.out.println ("Date====>" +date); if(TSinstanceofDate) {TS= (Timestamp) date;//Conversion} System.out.println ("Ts=====>" +ts); }}
Test Code
Conversions between dates