The Java.util.Date class in Java 8 adds two methods, namely the From (Instant Instant) and Toinstant () methods
Obtains an instance of the date from a Instant object.public static Date from (Instant Instant) {try {return NE W Date (Instant.toepochmilli ()); } catch (ArithmeticException ex) {throw new IllegalArgumentException (ex); }}//converts this Date object to an instant.public Instant toinstant () {return Instant.ofepochmilli (GetTime ());}
These two methods allow us to easily implement the old date class into a new date class, the idea is to use instant when the intermediary, and then through the instant to create localdatetime (this class can easily get localdate and localtime), The new date class is also the same as the old one, the new first turn to LocalDateTime, then get the instant, and then turn to date, the specific implementation details are as follows:
01. java.util.Date --> java.time.LocalDateTimepublic void Udatetolocaldatetime () { java.util.Date date = new Java.util.Date (); instant instant = date.toinstant (); zoneid zone = zoneid.systemdefault (); localdatetime Localdatetime = localdatetime.ofinstant (Instant, zone);} 02. java.util.date --> java.time.localdatepublic void udatetolocaldate () { java.util.date date = new java.util.date (); instant instant = date.toinstant (); zoneid zone = zoneid.systemdefault (); localdatetime localdatetime = Localdatetime.ofinstant (Instant, zone); localdate localdate = Localdatetime.tolocaldate ();} 03. java.util.date --> java.time.localtimepublic void udatetolocaltime () { java.util.date date = new java.util.date (); instant instant = date.toinstant (); zoneid zone = zoneid.systemdefault (); localdatetime localdatetime = Localdatetime.ofinstant (Instant, zone); localtime localtime = Localdatetime.tolocaltime ();} 04. java.time.LocalDateTime --> java.util.Datepublic void Localdatetimetoudate () { LocalDateTime localDateTime = Localdatetime.now (); zoneid zone = zoneid.systemdefault (); instant instant = localdatetime.atzone (Zone). Toinstant (); Java.utiL.date date = date.from (instant);} 05. java.time.localdate --> java.util.datepublic void localdatetoudate () { localdate localdate = localdate.now (); Zoneid zone = zoneid.systemdefault (); instant instant = Localdate.atstartofday (). Atzone (Zone). Toinstant (); java.util.date date = date.from (instant);} 06. java.time.localtime --> java.util.datepublic void localtimetoudate () { localtime localtime = localtime.now (); Localdate localdate = localdate.now (); localdatetime localdatetime = localdatetime.of (localdate, localtime); zoneid zone = Zoneid.systemdefault (); instant Instant = localdatetime.atzone (Zone). Toinstant (); java.util.date date = date.from (instant);}
In Java 8, date and LocalDateTime, Localdate, localtime