Java8 new time and date library and usage examples

Source: Internet
Author: User
Tags time zones local time new set time and date

Java8 introduced a new set of time and date APIs, and this essay will illustrate the API for learning Java8.

Java. In the time package, the class is immutable and thread-safe. The new time and date APIs are located in Java.time, and the following are key classes

instant--It represents a time stamp.

The localdate--does not contain specific time dates, such as 2014-01-14. It can be used to store birthdays, anniversaries, entry dates, etc.

localtime--it represents a time without a date.

localdatetime--it contains the date and time, but there is no offset or time zone.

zoneddatetime--This is a complete datetime that contains the time zone, and the offset is based on utc/GMT. Java8 How to deal with the time and date

1. How to get the date of the day in Java8

There is a class called localdate in the java8 that can be used to indicate today's date. This class is slightly different from Java.util.Date because it contains only dates and no time.

Localdate today = ();
System.out.println ("Today is----" +today);
 This is----2017-11-20

2. How to get the current date and year in Java8

The Localdate class provides some handy ways to extract dates and other date attributes, particularly handy, just use the corresponding getter method, very intuitive

       Localdate today = ();
       int year = Today.getyear ();
       int month = Today.getmonthvalue ();
       int day = Today.getdayofmonth ();
       System.out.println ("Year:" +year);
       System.out.println ("Year:" +month);
       System.out.println ("Year:" +day);
       /* year:2017

3. How to get a specific date in JAVA8

With another method, you can create any date that accepts an argument for the date of the month and then returns an equivalent localdate instance. In this method, the date you need to fill in what is what, do not want the previous API month must start from 0

4. Check if two dates are equal in JAVA8

Localdate overrides the Equals method to compare dates, as follows:

5, in the Java8 how to check repeat events, such as birthdays

Another task in Java that is related to time and date is to check for recurring events, such as the monthly billing day.

How to determine whether a holiday or a recurring event in Java uses the MonthDay class. This class is composed of the month day, does not contain year information, and can be used to represent some dates or other combinations that recur each year. He is as immutable and thread-safe as the other classes in the new Date library, and it is also a value class.

The monthday can be seen to store only the month, compared to two days of the month to know whether to repeat

6. How to get the current time in Java8

This is very similar to getting the current date with the first example, where the LocalTime class is used, and the default format is hh:mm:ss:nnn

As you can see, this time is not inclusive of dates

7. How to increase the number of hours in the time

Many times you need to work with time, such as adding one hours to calculate the time, JAVA8 provides a more convenient method such as Plushours, which returns a reference to a new localtime instance, because LocalTime is immutable

8, how to get 1 weeks after the date

This is similar to the previous example of getting 2 hours, where we get a date of 1 weeks. Localdate is used to indicate a date without time, he has another plus () method can be used to increase the day, week, month, Chronounit is used to represent the time unit, Localdate is also immutable, so any modification operation will return a new instance

You can see what the date is after a week, or you can use this method to add one months, one year, one hour, one point, etc.

9, a year before and after the date

In the last example we used the Localdate Plus () method to increase the day-week for the date, and now we use the minus () method to find the day of the year

10, use the clock in the JAVA8

JAVA8 has its own clock class, which can be used to get the current instantaneous time and date of a time zone (so sensitive to time zones). To replace the System.currenttimelnmillis () and Timezone.getdefault () method

11, in Java How to determine whether a date in front of another date or behind

How to determine whether a date is before or after another date, and in Java8, the Localdate class uses the Isbefore (), Isafter (), Equals () method to compare two dates. The Isbefore () method returns True if the date of the call method is earlier than the given date. The Equals () method is illustrated in the previous example, and there is no example

You can see that the comparison date in Java8 is so simple that you no longer need to use another class like calendar to accomplish a similar task.

12. Handle different time zones in Java8

The Java8 not only separates dates and times, but also time zones. For example, Zonid represents a particular time zone, Zoneddatetime represents the time zone, equivalent to the previous GregorianCalendar class. With this class, you can convert the local time to the corresponding time in another time zone.

Note: The corresponding time zone text can be manually filled in, you can also call the defined, manually fill in when the attention can not fill the wrong, or you will encounter the following exception

13, how to indicate a fixed date, such as credit card expiration time

Just as MonthDay represents a recurring day, Yearmonth is a different combination, representing dates such as credit card repayment days, term deposit maturity, and options expiration date. You can use this class to find out how many days this month, lengthofmonth () This method returns the Yearmonth instance of how many days, this is useful to check whether February run February

14. How to check leap year in JAVA8

The Localdate class consists of a isleapyear () method that returns whether the current localdate corresponds to a leap year

15. How many days and months are included between two dates

Calculates how many days, weeks, months, and years are included between two dates. You can use the Java.time.Period class to complete this feature. In the following example, there are a few months between the calculated date and the future date.

16. Date and time with timezone

In Java8, you can use Zoneoffset to represent a time zone, and you can use its static method Zoneoffset.of () method to get the corresponding time zone, as long as you get this offset, You can create a new offsetdatetime with this offset and localdatetime.

can see now date and Time Zone Association, note that Offsetdatetime is mainly used for machine understanding, usually use the front end of the Zonedatetime class can be

17. Get the current timestamp in java8

Java8 getting timestamps is particularly simple. Instant class by a static Factory method now () can return the current timestamp

As you can see, the current timestamp contains the date and time, similar to java.util.Date, in fact Instant is java8 previous date, and you can use the methods in this two class to convert between the two types, such as Date.from (Instant) is used to convert instant into, and date. Toinstant () is the conversion of date into instant

18. How to parse/format a date using a predefined formatter in Java8

Before JAVA8, the format of the time date is cumbersome and often formatted with SimpleDateFormat, but SimpleDateFormat is not thread-safe. In Java8, a new thread-safe date and time formatter is introduced. and the predefined format is well defined. For example, the basicisodate format used in this example formats the 20160414 format into 2016-04-14

There are a lot of well-defined formats in the DateTimeFormatter, and you can go and see for yourself.

19, how to use the custom formatter in Java to resolve the date

In the example above, we used the preset time date format to parse the date string, but sometimes the preset is not satisfied when we need to customize the date formatter, the following example date format is "MM DD yyyy". You can pass in any pattern to DateTimeFormatter's Ofpattern static method (), which returns an instance of the same literal as in the preceding example. For example, M represents the month, M still stands for points, invalid mode throws abnormal datetimeparseexception.

20, how to format the date in the Java8, converted to a string

In the previous two examples, we mainly parse the date string to date, and in this case we convert the date to a character instead. Here we have an instance of the LocalDateTime class, and we're going to convert him into a formatted date string, and the same as the previous example, we still need to develop a pattern string to create an instance of the DateTimeFormatter class, but the call is Localdate.format ( )。 This method returns a string representing the current date, and the corresponding pattern is defined in the DateTimeFormatter instance that is passed in.

The conversion of 21,date and Localdate

Date date = new Date ();
        Instant Instant = Date.toinstant ();
        ZoneID ZoneID = Zoneid.systemdefault ();
        The Atzone () method returns the zoneddatetime generated from this instant in the specified time zone.
        localdate localdate = Instant.atzone (ZoneID). Tolocaldate ();
        System.out.println ("date =" + date);
        System.out.println ("localdate =" + localdate);
       /* Date = Mon Nov 09:58:50 CST 2017
        localdate = 2017-11-20*/

ZoneID ZoneID = Zoneid.systemdefault ();
        Localdate localdate = ();
        Zoneddatetime ZDT = Localdate.atstartofday (ZoneID);
        Date date = Date.from (Zdt.toinstant ());
        System.out.println ("localdate =" + localdate);
        System.out.println ("date =" + date);
        /*localdate = 2017-11-20
        Date = Mon Nov 00:00:00 CST 2017*/

several key points of the date and time API in Java8

After the example above, we have a certain understanding of the time and date of java8, and now review

It provides javax.time.ZoneId for processing time zones.

It provides the localdate and LocalTime classes

All classes in the new time and date APIs in Java 8 are immutable and thread-safe, as opposed to the previous date and calendar APIs, It's like java.util.Date and SimpleDateFormat. These key classes are not thread-safe.

One important point in the new time and date API is that it defines the basic concept of time and date, such as instantaneous time, duration, date, time, timezone, and time period. They are all based on the ISO calendar system.

Each Java developer should at least be aware of these five classes in this new set of APIs:

Instant it represents a timestamp, such as 2016-04-14t14:20:13.592z, which can be obtained from the Java.time.Clock class, like this: Instant current = Clock.system (Zoneid.of ( "Asia/tokyo")). Instant ();

Localdate it represents a date without time, such as 2016-04-14. It can be used to store birthdays, anniversaries, entry dates, etc.

LocalTime-it represents a time without a date

LocalDateTime-it contains time and date, but no offset with time zone

Zoneddatetime-This is a complete time with time zone, which is adjusted for time zone according to utc/GMT

The main package for this library is Java.time, which contains classes that represent dates, times, instants, and durations. It has two package, one is Java.time.foramt, this is what the use is very obvious, there is a java.time.temporal, it can from the lower level of each field access.

The time zone refers to the area on the earth that shares the same standard. Each time zone has a unique identifier, along with the format of a region/city (Asia/tokyo) and an offset time starting from Greenwich. For example, Tokyo's shift time is +09:00.

The Offsetdatetime class actually contains LocalDateTime and Zoneoffset. It is used to represent a full date (month and day) and time (minutes, nanoseconds) of a Greenwich Mean period offset (+-hour: +06:00 or -08:00).

The DateTimeFormatter class is used to format and parse dates in Java. Unlike SimpleDateFormat, it is immutable and thread-safe, and can be assigned to a static variable if needed. The DateTimeFormatter class provides a number of predefined formats, and you can customize the format you want. Of course, according to the Convention, it also has a parse () method that converts a string to a date and throws a Datetimeparseexception exception if any errors occur during conversion. Similarly, the Dateformatter class also has a format () method for formatting dates that, if it goes wrong, throws a Datetimeexception exception.

Again, "MMM D yyyy" and "MMM DD yyyy" The two date formats are also slightly different, the former can identify the "2 2014" and "the 14 2014" of these two strings, and the latter if the transmission came in "a long time 2 2014" will be an error, Because it expects the month to pass in two characters. In order to solve this problem, in the case of a single digit, you have to fill in the front 0, such as "2 2014", should be replaced by "02 2014".

This is the new time and date API on Java 8. These few short examples are sufficient to understand some of the new classes in this set of APIs. We learned how to create and modify date instances. We also know the difference between a pure date, a date plus time, a date overtime, how to compare two dates, how to find a day to a specific date, such as the next birthday, anniversary or insurance day. We also learned how to parse and format dates in a thread-safe way in Java 8 without having to use a thread-local variable or a third-party library. The new API is capable of any task related to time and date.

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.