Java8 New Time-date library and usage examples

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

From: Java translation station

Links: http://it.deepinmind.com/java/2015/03/17/20-examples-of-date-and-time-api-from-Java8.html

English: http://javarevisited.blogspot.sg/2015/03/20-examples-of-date-and-time-api-from-Java8.html

In this paper, according to the above information to organize and modify the explanation

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

Java. The time package is that the class is immutable and thread-safe. The new time and date API is in Java.time, and here are some of the key classes

instant--it represents a timestamp.

localdate--does not include dates for specific times, such as 2014-01-14. It can be used to store birthdays, anniversaries, onboarding dates and more.

localtime--it represents a time without a date

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

zoneddatetime--This is a full datetime with a time zone, and the offset is based on the utc/GMT.

How the JAVA8 handles time and date

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

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

As you can see, he created today's date without containing time information and formatted the date.

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

Localdate class provides a number of convenient methods can be used to extract dates and other date attributes, especially convenient, only need to use the corresponding getter method is possible, very intuitive

3. How to get a specific date in JAVA8

In another way, you can create any date that accepts a parameter of month and day, and then returns an equivalent localdate instance. In this method, the required date you fill out is what you don't want to be in the API before the month must start from 0

4. Check if two dates are equal in JAVA8

Localdate overrides the Equals method to make a date comparison, as follows:

5. How to check for recurring events in Java8, such as birthdays

In Java there is also a time-date-related task that checks for recurring events, such as the monthly billing day

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

By using the MonthDay, you can see that the date is only stored for the month, and you will be able to tell if you repeat it by comparing two dates.

6. How to get the current time in Java8

This is very similar to the first example to get the current date, here is the LocalTime class, the default format is hh:mm:ss:nnn

Can see that this time is not included in the date

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

Many times need to operate on time, such as one hours to calculate the time after, JAVA8 provides a more convenient method such as Plushours, these methods return 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 example of the previous 2-hour time, where we get the date after 1 weeks. Localdate is used to denote a date without time, and 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, a year, an hour, a minute, and so on.

9. Dates around the year

In the previous example, we used the Localdate Plus () method to add a day-week to the date, and now we use the minus () method to find out the day of the year before.

10. Use the clock in the JAVA8

The java8 comes with a clock class that can be used to obtain the current instantaneous time, date, and so on in a time zone that is sensitive to the time zone. Used instead of System.currenttimelnmillis () and Timezone.getdefault () methods

11. How to determine whether a date precedes or follows another date in Java

How to tell if a date is before or after another date or equal, in Java8, the Localdate class uses the Isbefore (), Isafter (), Equals () methods to compare two dates. The Isbefore () method returns True if the date of the calling method is earlier than the given date. The Equals () method has been explained in the previous example, and here is no example.

You can see that the comparison dates in Java8 are very simple and no longer need to use other classes like calendar to accomplish similar tasks.

12. Working with different time zones in Java8

The Java8 not only separates the date and time, but also the timezone. For example, Zonid represents a specific time zone, Zoneddatetime represents time with a time zone, equivalent to the previous GregorianCalendar class. Using this class, you can convert the local time to the corresponding time in another time zone.

Note: The corresponding time zone text can be directly filled in, you can also call the definition of a good, manually fill in the time to pay attention to not fill the wrong, otherwise you will encounter the following exception

13, how to express a fixed date, such as credit card expiry time

As MonthDay represents a recurring day, Yearmonth is another combination that represents a date such as credit card repayment date, term deposit expiry date, options expiry date. You can use this class to find out how many days this month, lengthofmonth () This method returns the number of days of this Yearmonth instance, which is useful for checking whether February is run February

14. How to check leap years in Java8

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

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

Calculates the number of days, weeks, months, and years that are included between two dates. You can use the Java.time.Period class to complete this function. In the following example, there are several months between the calculated date and the future date

16. Date and time with time zone

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 the offset is obtained. You can create a new offsetdatetime with this offset and localdatetime.

You can see the current time-date and TimeZone Association, note that Offsetdatetime is mainly used to understand the machine, usually used in front of the end of the Zonedatetime class can be

17. Get the current timestamp in java8

Java8 getting timestamps is particularly straightforward. The instant class is returned by a static factory method now () to return the current timestamp

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

18, how to parse/format dates using predefined formatters in Java8

Before Java8, time-date formatting was cumbersome and often used simpledateformat for formatting, but SimpleDateFormat was not thread-safe. In Java8, a new thread-safe date and time formatter was introduced. And the format is predefined. For example, the basicisodate format used in this example will format 20160414 as 2016-04-14

There are many well-defined formats in DateTimeFormatter, so you can take a look at them.

19. How to use a custom formatter in Java to parse a date

In the example above, we used the preset time-date formatter to parse the date string, but sometimes we need to customize the date formatter when the preset is not satisfied, and the date format in the following example is "MM dd yyyy". You can give DateTimeFormatter the Ofpattern static method () to pass in any pattern, it will return an instance, the pattern literal is the same as in the precedent. For example, M for the month, M still stands for points, invalid mode will throw abnormal datetimeparseexception.

20. How to format dates in JAVA8 and convert them to strings

In the previous two examples, we converted the date string to date, and in this example we converted the date into a character. Here we have an example of a LocalDateTime class, we want to convert him into a well-formed date string, as in 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 incoming DateTimeFormatter instance.

Java8 several key points in the date and time API

Through the above example, we have a certain understanding of the time and date of java8, and now look back

It provides javax.time.ZoneId to handle the time zone.

It provides the localdate and LocalTime classes

All classes in the new time and date API in Java 8 are immutable and thread-safe, which is the exact opposite of the previous date in the Calendar API. The key classes that face the java.util.Date and SimpleDateFormat are not thread-safe.

The important point in the new time and date API is that it defines the basic concepts of time and date, for example, instantaneous time, duration, date, time, time zone, and time period. They are all based on the ISO calendar system.

Every Java developer should know at least 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, onboarding dates and more.

LocalTime-it represents a time without a date

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

Zoneddatetime-This is a full time with a time zone, which adjusts the time zone according to utc/GMT

The main package of this library is Java.time, which contains classes representing the date, time, instantaneous, and duration of the time. It has two sub-package, one is Java.time.foramt, this is what the use is obvious, there is a java.time.temporal, it can be accessed from a lower level of the various fields.

Time zones refer to areas on the earth that share the same standard time. Each time zone has a unique identifier, along with the format of a region/city (Asia/tokyo) and an offset from Greenwich Mean time. For example, the offset time in Tokyo is +09:00.

The Offsetdatetime class actually contains LocalDateTime and Zoneoffset. It is used to represent a full date (month and day) and time (hour, minute, nanosecond) that contains the GMT offset (+/-hours: minutes, such as +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 formatters, and you can customize the format you want. Of course, according to the Convention, it also has a parse () method that is used to convert a string to a date, and throws a Datetimeparseexception exception if any errors occur during the conversion. Similarly, the Dateformatter class also has a format () method for formatting dates that throws an datetimeexception exception if it goes wrong.

Again, "Mmm d yyyy" and "MMM dd yyyy" Two date format also slightly different, the former can recognize the "Jan 2 2014" and "Jan 14 2014" Two strings, and the latter if the incoming is "Jan 2 2014" will be an error, Because it expects the month to pass in two characters. To solve this problem, in the case of single-digit days, you have to fill in the front 0, such as "Jan 2 2014" should be changed to "Jan 02 2014".

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

Java8 New Time-date library and usage examples

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: info-contact@alibabacloud.com 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.