The TIME-API_JDK of Jdk8

Source: Internet
Author: User
Tags time zones local time locale time and date timezones

Reproduced from:

The drawbacks of java.util.Date and calendar classes before 1.JAVA8

1 at the very beginning, date is not only to host dates information, but also to do the conversion between dates, and to do different date format display, the responsibility is more complex (do not observe a single responsibility).

Later, starting with JDK 1.1, these three responsibilities were separated:
Use the Calendar class to implement conversion between date and Time fields, use the DateFormat class to format and parse a date string, and date only to host day and time information. The corresponding method in the original date is now deprecated. Both date and calendar are too inconvenient to use, and this is where the API is not designed.

2 The Silent Year and month (month is starting from 0)


[Java] View plain copy date = new Date (2016,1,1);    SYSTEM.OUT.PRINTLN (date); Output result: Tue Feb 00:00:00 CST 3916
The result of this year is 2012+1900, and month clearly given the parameter is 1, but the output is February.

Set date can be used Java.util.Calendar

[Java] View plain copy Calendar calendar = Calendar.getinstance ();   Calendar.set (2016, 5, 2); Although the calendar year's pass value does not need to subtract 1900, but the calendar's month also starts from 0, expressed May should use 4 this number.

3 all the properties in Java.util.Date and Java.util.Calendar are variable and the thread is unsafe.


[java]  View plain  copy public class test {           public static void main (String[] args)  {            calendar birth = calendar.getinstance ();            birth.set (1975, calendar.may, 26);            calendar now = calendar.getinstance ();            system.out.println (Daysbetween (birth, now)); //  output is 14963, the value is not fixed            system.out.println (Daysbetween (Birth, now));  //  output   Display  0.           }  }       public  Static long daysbetween (calendar begin, calendar end)   {               long daysbetween  = 0;               while ( Begin.before (end))  {                    begin.add (calendar.day_of_month, 1);                    daysBetween++;              }               return daysBetween;          }       }   Note:daysbetween has a problem, if you count two date instances in a row, you'll get 0 for the second time because the calendar state is variable, considering the situation where the repetition is calculated, It is best to copy a new calendar. Modify the code as follows
[java]  View Plain  copy public static long daysbetween (calendar begin,  Calendar end)  {          calendar calendar =   (Calendar)  begin.clone (); //  replication                long daysBetween = 0;               while (Calendar.before (end))  {                   calendar.add (calendar.day_of_month, 1);                   daysBetween++;               }              return daysBetween;         }   

2. Brief introduction of the new Date time API

Java has a long history of date and time APIs, and the format class for time, date, and other time dates in the previous version of Java 8 has been criticized for thread safety, heavyweight, and high serialization cost issues. Java 8 absorbs the essence of joda-time and creates an excellent API for Java with a new start. The new java.time contains all about clocks (Clock), local date (localdate), local time (localtime), Local date time (LocalDateTime), Class for Time zone (Zoneddatetime) and Duration (Duration). The historic date class adds the Toinstant () method, which is used to convert Date to a new representation. These new localized time and date APIs greatly simplify the management of date time and localization.

At present, Java8 has added the rule of the class representation date-time concept of java.time package definition, which is very convenient to use; The most important point is that the value is immutable and thread safe.

The following figure is a format for the date-time values of some of the main classes under the Java.time package for easy understanding of use:

Note: However, despite the new API, there is still a serious problem-a lot of old code and libraries are still using the old APIs. Now, Java 8 solves this problem by adding a new method Toinstant () to the date class that converts date to a new instance. This allows you to switch to the new API.

For the new API:
Very useful value types: Instant-----Similar to java.util.Date zoneddatetime-----ZoneID-time zones are important when using offsetdatetime-----offsettime, Zoneoff Set-offset processing for UTC Duration, Period-----But if you want to find the amount of time between two dates, you may be looking for chronounit instead (see below for details) other useful types: datetimeformatter----- Converts a date type to a string type Chronounit-----Calculates the amount of time between two points, such as ChronoUnit.DAYS.between (T1, T2) temporaladjuster-----such as Date.with ( Temporaladjuster.firstdayofmonth ())

Note: In most cases, the new value type is supported by JDBC. There is a small number of exceptions, Eg:zoneddatetime have no corresponding (type) in SQL.

3.Java the difference between the old and new date APIs

Class 4.1 Clock class under the package

The clock class provides a way to access the current date and time. Clock uses the time zone to access the current instant, date, and moment. The clock class can replace System.currenttimemillis () and Timezone.getdefault ().


[java]  View plain  copy//clock  clock                 clock clock1 = clock.systemdefaultzone ()//Get system default time zone   (current instantaneous time  )                system.out.println (  " System time Date: "+clock1.instant ()  );                system.out.println (  Time MS: "+clock1.millis ()  );                                        final Clock clock =  CLOCK.SYSTEMUTC ()//Get the system clock and convert it to the date and time using the UTC time Zone                 system.out.println (  "Date:" +clock.instant ()  );                 system.out.println (  Time millisecond value: "+clock.millis ()  );  

Output Result: System time Date: 2016-05-12t07:42:37.883z time MS: 1463038957894

Time Date: 2016-05-12t07:42:37.894z

Time millisecond Value: 1463038957894

A particular point in time can also be represented using the instant class, which can also be used to create old Java.util.Date objects.


[Java] View plain copy Instant Instant = Clock1.instant ();                Date javadate = Date.from (instant); System.out.println ("Date:" +javadate);

Output results:

Date:thu May 15:47:00 CST 2016

4.2 ZoneID (Time zone)

In the new API, the time zone is represented using ZoneID. Time zones can be easily obtained by using the static method of (). Time zones define the time difference to UTS times and are extremely important when converting between instant Point-in-time objects to local date objects.


[Java] View plain copy//Output all visible time zones Id,eg:asia/aden, America/cuiaba, etc/gmt+9 System.out.println (Zoneid.getavailablez      Oneids ());   ZoneID zone1 = Zoneid.of ("Europe/berlin");   ZoneID zone2 = Zoneid.of ("Brazil/east");   System.out.println (Zone1.getrules ());   System.out.println (Zone2.getrules ()); Output result: zonerules[currentstandardoffset=+01:00]//Output result: zonerules[currentstandardoffset=-03:00]

4.3 localtime (local time)

LocalTime defines a time when there is no time zone information.


1 Get the current local time

[Java] View plain copy//Get the local date and local time final localtime time = ();               Final localtime timefromclock = (clock);               System.out.println (time);   System.out.println (Timefromclock); Output results:


2 Show time in time area

[Java] View plain copy ZoneID zone1 = Zoneid.of ("Europe/berlin");                      ZoneID zone2 = Zoneid.of ("Brazil/east");           LocalTime Now1 = (Zone1);           LocalTime now2 = (zone2);            System.out.println ("Time zone: Europe/berlin---" +now1); System.out.println ("Time zone: Brazil/east---" +now2);

Output results:

TimeZones: Europe/berlin---10:03:23.217
TimeZones: Brazil/east---05:03:23.217

LocalTime provides a variety of factory methods to simplify the creation of objects, including parsing time strings.


[Java] View plain copy localtime late = Localtime.of (22, 12, 18);/hour SEC System.out.println (late);                   Output result: 22:12:18 datetimeformatter germanformatter = Datetimeformatter.oflocalizedtime (formatstyle.short)              . Withlocale (Locale.german);           LocalTime leettime = Localtime.parse ("15:39", Germanformatter); System.out.println (Leettime); Output results: 15:39

4.4 localdate (local date)

Localdate represents an exact date (eg:2014-03-11). The value of the object is immutable and is basically consistent with the localtime.


[Java] View plain copy Clock Clock = Clock.systemdefaultzone ()//Get the system default time zone (current instantaneous time)//Gets the local date           and local time final localdate date = ();           Final Localdate Datefromclock = (clock);           SYSTEM.OUT.PRINTLN (date);   System.out.println (Datefromclock); Output results:


Parsing a localdate type from a string is as simple as parsing the localtime.


[Java] View plain copy datetimeformatter Germanformatter = datetimeformatter.oflocalizeddate (formatstyle.medium)      . Withlocale (Locale.german);   Localdate Xmas = localdate.parse ("25.10.2016", Germanformatter);   System.out.println (xmas); Output results:


4.5 LocalDateTime (local date time)

Represents a specific time and date. LocalDateTime and LocalTime, as well as localdate, are immutable. LocalDateTime provides a number of ways to access specific fields.



[Java] View plain copy Clock Clock = Clock.systemdefaultzone ()//Get the system default time zone (current instantaneous time)//Gets the local date/           Time Final LocalDateTime datetime = ();           Final LocalDateTime Datetimefromclock = (clock);           SYSTEM.OUT.PRINTLN (datetime);   System.out.println (Datetimefromclock); Output results:



[Java] View plain copy LocalDateTime sylvester = Localdatetime.of (2016, Month.december, 31, 23, 59, 59);       DayOfWeek DayOfWeek = Sylvester.getdayofweek ();                     System.out.println (DayOfWeek);       Month Month = Sylvester.getmonth ();                       SYSTEM.OUT.PRINTLN (month);       Long Minuteofday = Sylvester.getlong (Chronofield.minute_of_day); System.out.println (Minuteofday);

Output results:

As long as the time zone information is appended, it can be converted to a Point-in-time instant object, and the instant object can easily be converted to an old-fashioned java.util.Date.

[Java] View plain copy LocalDateTime sylvester = Localdatetime.of (2016, Month.december, 31, 23, 59, 59);                       Instant Instant = Sylvester. Atzone (Zoneid.systemdefault ()). Toinstant ();           Date legacydate = Date.from (instant); System.out.println (legacydate);

Output results:

Sat Dec 23:59:59 CST 2016

Formatting localdatetime and formatting times and dates, I can customize the format in addition to using predefined formats.


[Java] View plain copy datetimeformatter formatter = Datetimeformatter.ofpattern ("MM DD, yyyy-hh:mm");       LocalDateTime parsed = Localdatetime.parse ("MB, 2016-07:13", formatter);       String string = Formatter.format (parsed);   System.out.println (string); Output results:
05 03, 2016-07:13

Note: Unlike Java.text.NumberFormat is the new version of the DateTimeFormatter is immutable, so it is thread-safe.

4.6 Zoneddatetime (DateTime and Time zone information)

With Zoneddatetime, it holds the date and time of the ISO-8601 date system and has time zone information.


[Java] View plain copy Clock Clock = Clock.systemdefaultzone ()//Get system default time zone (current instantaneous time)//Getting the zoned Date/time FINA   L Zoneddatetime zoneddatetime = ();   Final Zoneddatetime Zoneddatetimefromclock = (clock);   Final Zoneddatetime Zoneddatetimefromzone = (Zoneid.of ("America/los_angeles"));   System.out.println (Zoneddatetime);   System.out.println (Zoneddatetimefromclock); System.out.println (Zoneddatetimefromzone);

Output results:

4.7 Duration Class

Duration hold the time accurate to nanosecond. It's easy to calculate the difference between two dates.

Eg: to find a time lag

[Java] View plain copy//Get duration between two dates final LocalDateTime from = Localdatetime.of (201   4, Month.april, 16, 0, 0, 0);//month day time seconds final LocalDateTime to = Localdatetime.of (2015, Month.april, 16, 23, 59, 59);   Final Duration Duration = Duration.between (from, to);   System.out.println ("Duration in the Days:" + duration.todays ()); System.out.println ("Duration in Hours:" + duration.tohours ());</span>

Output results:
Duration in days:365
Duration in hours:8783

There is also a way to get the time difference: chronounit

[java]  View plain  copy zoneid zone1 = zoneid.of ("America/cuiaba");             zoneid zone2 = zoneid.of ("Brazil/East");             localtime now1 = ( ZONE1);            LocalTime now2 = (zone2);            long hoursbetween  = chronounit.hours.between (now1, now2);             long minutesbetween = chronounit.minutes.between (NOW1,&NBSP;NOW2);            system.out.println (Hoursbetween); // 1    &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN (Minutesbetween); //  60  

5. New Date Time API sample

Eg: (note: Be interested in your own running results try various methods, very easy.) )

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.