Common usage examples in Java 8 time and date library
Someone asked me what is the best way to learn a new library? My answer is to use it in real projects. In a real project, there will be various requirements, which will urge developers to explore and study this new library. In short, only the task itself will really urge you to explore and learn. So is the new date and time API of Java 8. In order to learn this new library of Java 8, here I have created 20 task-oriented examples. Let's start with a simple task, such as how to use the time and date library of Java 8 to represent today, then further generate a complete date with time and time area, and then study how to complete some more practical tasks, such as developing a reminder application to find out the distance from some specific dates, such as birthday, Sunday anniversary, How many days are there for the next billing day, the next premium day, or the expiration time of the credit card.
Example 1 how to get the date of the day in Java 8
There is a class called localdate in Java 8, which can be used to represent today's date. This class is similar to Java util. Date is slightly different because it contains only date and no time. Therefore, if you only need to represent the date without including the time, you can use it.
You can see that it creates today's date without time information. It also formats the date and then outputs it. Unlike the previous date class, the printed data is unformatted.
Example 2 how to get the current month, year and day in Java 8
The localdate class provides some convenient methods that can be used to extract the year, month, day and other date attributes. Using these methods, you can get any date attribute you need instead of using Java util. A class like calendar:
It can be seen that it is very simple to obtain the year and month information in Java 8. Just use the corresponding getter method. There is no need to remember. It is very intuitive. You can compare it with the old way of getting the current month, year and day in Java.
Example 3 how to get a specific date in Java 8
In the first example, we see that it is very simple to generate the current day date through the static method now (), but through another very useful factory method localdate Of (), you can create any date, which accepts the parameters of year, month and day, and then returns an equivalent localdate instance. Another good news about this method is that it does not make mistakes in the previous API. For example, the year can only start in 1900, the month must start from 0, and so on. The date here is what you write. For example, in the following example, it represents January 14. There is no hidden logic.
It can be seen that the created date is what we wrote, January 14, 2014.
Example 4 how to check whether two dates are equal in Java 8
When it comes to the actual task of processing time and date in reality, it is common to check whether the two dates are equal. You may often have to judge whether today is a special day, such as birthday, anniversary, or holiday. Sometimes, you will be given a date to check whether it is a day, such as a holiday. The following example will help you complete such tasks in Java 8. As you can imagine, localdate overrides the equals method to compare dates, as shown below:
In this example, the two dates we compare are equal. At the same time, if you get a formatted date string in the code, you have to parse it into a date before you can compare it. You can compare this example with the way Java compares dates before, and you will find that it is much better.
Example 5 how to check for duplicate events, such as birthdays, in Java 8
Another practical task related to time and date in Java is to check for duplicate events, such as monthly billing day, wedding anniversary, monthly repayment date or the date of annual insurance premium payment. If you work in an e-commerce company, there must be a module that sends birthday wishes to users and sends greetings to them on every important holiday, such as Christmas and Thanksgiving, In India, it may be the Lantern Festival (deepawali). How to judge whether it is a festival or a recurring event in Java? Use the monthday class. This class consists of months and days and does not contain year information, that is, you can use it to represent some recurring days every year. Of course, there are other combinations, such as the Yearmonth class. It is immutable and similar to other classes in the new time and date library Thread safe, and it is also a value class. Let's take an example to see how to use monthday to check a duplicate date:
Although the years are different, today is the birthday, so you will see a birthday wish there. You can adjust the system time and run this program to see if it can remind you when your next birthday is. You can also try to write a JUnit unit test with your next birthday to see if the code can run correctly.
Example 6 how to get the current time in Java 8
This is very similar to getting the current date in the first example. This time we use a class called Localtime, which is a time without date and is close relative to localdate. Here you can also use the static factory method now () to get the current time. The default format is HH: mm: SS: NNN, where NNN is nanosecond. It can be compared with how Java 8 used to get the current time.
You can see that the current time does not contain dates, because Localtime has only time and no date.
Example 7 how to increase the number of hours in the time
Many times we need to add hours, minutes or seconds to calculate the future time. Java 8 not only provides immutable and thread safe classes, but also provides some more convenient methods, such as plushours () to replace the original add () method. By the way, these methods return a reference to a new Localtime instance. Because Localtime is immutable, don't forget to store the new reference.
You can see that the current time is 16:33:33.369 two hours later. Now you can compare it with the old way of adding or reducing hours in Java. You can see which way is better at a glance.
Example 8 how to get the date after 1 week
This is similar to the previous example of getting the time after 2 hours. Here we will learn how to get the date after 1 week. Localdate is used to represent a date without time. It has a plus () method to add days, weeks, or months. Chrononunit is used to represent this time unit. Since localdate is also immutable, any modification will return a new instance, so don't forget to save it.
You can see the date after 7 days, that is, a week. You can use this method to add a month, a year, an hour, a minute, or even ten years. Check the chrononunit class in the Java API for more options.
Example 9 dates around one year
This is a sequel to the last example. In the above example, we learned how to use the plus () method of localdate to add a day, week or month to the date. Now let's learn how to use the minus () method to find the day a year ago.
It can be seen that there are two years now, one is 2013 and the other is 2015, respectively around 2014.
Example 10 using a clock in Java 8
Java 8 comes with a clock class. You can use it to get the current instantaneous time, date or time in a time zone. You can use clock instead of system Currenttimeinmillis() and timezone Getdefault() method.
You can compare this clock with the specified date, such as the following:
This is quite convenient if you need to process dates in different time zones.
Example 11 how to determine whether a date is before or after another date in Java
This is also a common task in actual projects. How do you judge whether a date is before or after another date, or exactly equal? In Java 8, the localdate class has an isbefore () and isafter () method that can be used to compare two dates. If the date on which the method is called is earlier than the given date, the isbefore () method returns true.
As you can see, date comparison in Java 8 is very simple. There is no need to use another class like calendar to complete similar tasks.
Example 12 handles different time zones in Java 8
Java 8 not only separates the date and time, but also the time zone. Now there are several time zone related classes. For example, zonid represents a specific time zone, while zoneddatetime represents the time with time zone. It is equivalent to the Gregorian calendar class before Java 8. Using this class, you can convert the local time into the corresponding time in another time zone, such as the following example:
You can compare it with the previous method of converting local time into GMT time. By the way, as before Java 8, don't get the text corresponding to the time zone wrong, otherwise you will encounter such an exception:
Example 13 How to represent a fixed date, such as the expiration time of a credit card
Just as monthday represents a recurring day, Yearmonth is another combination, which represents dates such as credit card repayment date, time deposit maturity date and options maturity date. You can use this class to find out the number of days in that month. The lengthofmonth () method returns the number of days in the Yearmonth instance, which is very useful for checking whether February is 28 days or 29 days.
Example 14 how to check leap years in Java 8
This is not complicated. The localdate class has an isleapyear () method that can return whether the year corresponding to the current localdate is a leap year. If you still want to build wheels repeatedly, you can look at this code, which is a logic written in pure java to judge whether a year is a leap year.
You can check a few more years to see if the results are correct. It's best to write a unit test to test the normal year and leap year.
Example 15 how many days and months are included between two dates
Another common task is to calculate the number of days, weeks or years between two given dates. You can use Java time. Period class to complete this function. In the following example, we will calculate a total of several months between the current date and a future date.
As you can see, this month is January, and the release date of Java 8 is March, so there is a gap of two months.
Example 16 date and time with time zone offset
In Java 8, you can use zoneoffset class to represent a time zone. For example, India is GMT or utc5:30. You can use its static method zoneoffset Of () method to get the corresponding time zone. As long as you get the offset, you can create an offsetdatetime with the localdatetime and the offset.
You can see that the time and date are now associated with the time zone. Another point is that offsetdatetime is mainly for machines to understand. If it is for people to see, you can use the zonedatetime class.
Example 17 how to get the current timestamp in Java 8
If you remember how to get the current timestamp before Java 8, it's a piece of cake now. The instant class has a static factory method, now(), which can return the current timestamp, as follows:
It can be seen that the current timestamp contains date and time, which is similar to Java util. Date is very similar. In fact, instant is the date before Java 8. You can use the methods in these two classes to convert between these two types, such as date From (instant) is used to convert instant into Java util. Date, and date Toinst() is the to convert date to instant.
Example 18 how to use a predefined formatter to parse / format a date in Java 8
Before Java 8, the formatting of time and date was a technical job. Our good partner simpledateformat was not thread safe, and it seemed a little cumbersome if it was used as a local variable. Thanks to thread local variables, this makes it useful in a multithreaded environment, but Java has maintained this state for a long time. This time it introduces a new thread safe date and time formatter. It also comes with some predefined formatters, including common date formats. For example, in this example, we use the predefined basiisodate format, which will format February 14, 2014 as 20140114.
You can see that the generated date matches the value of the specified string, that is, the date format is slightly different.
Example 19 how to use a custom formatter to parse dates in Java
In the above example, we used the built-in time and date formatter to parse the date string. Of course, predefined formatter is really good, but sometimes you may still need to use custom date format. At this time, you have to create a custom date formatter instance yourself. The date format in the following example is "MMM DD yyyy". You can pass in any pattern to the ofpattern static method () of datetimeformatter, and it will return an instance. The literal amount of this pattern is the same as that in the previous example. For example, m still represents month, and M is still minute. Invalid patterns will throw datetimeparseexception exceptions, but if it is a logical error, for example, use m when you should use M, so there is no way.
You can see that the value of the date does match the incoming string, but the format is different.
Example 20 how to format a date into a string in Java 8
In the above two examples, although we use the datetimeformatter class, we mainly parse the date string. In this example, we have to do the opposite. Here we have an instance of the localdatetime class, which we want to convert into a formatted date string. This is by far the easiest and most convenient way to convert a date into a string in Java. The following example will return a formatted string. As in the previous example, we still need to use the specified pattern string to create an instance of datetimeformatter class, but what we call is not the parse method of localdate class, but its format () method. This method will return a string representing the current date, and the corresponding pattern is defined in the incoming datetimeformatter instance.
It can be seen that the current time is represented by the given "MMM DD yyyy HH: mm a" mode, which includes the month represented by three letters and the time represented by am and PM.
Several key points of date and time API in Java 8
After reading these examples, I believe you have a certain understanding of the new time and date API of Java 8. Now let's review some key elements of this new API.
1. It provides javax time. Zoneid is used to process time zones. 2. It provides localdate and Localtime classes. 3. All classes in the new time and date API in Java 8 are immutable and thread safe, which is just opposite to that in the previous date and calendar API, which is like Java util. The key classes date and simpledateformat are not thread safe. 4. An important point in the new time and date API is that it clearly defines the basic concepts of time and date, such as instantaneous time, duration, date, time, time zone and time period. They are all based on the ISO calendar system. 5. Every java developer should know at least the five classes in this new API:
6. The main package of this library is Java Time, which contains classes representing date, time, instantaneous and duration. It has two sub packages, one is Java time. For AMT, the purpose of this is obvious. Another one is Java time. Temporary, which can access each field from a lower level. 7. Time zone refers to the area on the earth that shares the same standard time. Each time zone has a unique identifier, as well as the format of a region / city (Asia / Tokyo) and an offset time from Greenwich mean time. For example, the offset time in Tokyo is + 09:00. 8. The offsetdatetime class actually contains localdatetime and zoneoffset. It is used to represent a complete date (mm / DD / yyyy) and time containing the Greenwich mean time offset (+ / - hours: minutes, such as + 06:00 or - 08:00) (hour, minute, second, nanosecond). 9. Datetimeformatter class is used to format and parse dates in Java. Unlike simpledateformat, it is immutable and thread safe. If necessary, it can be assigned to a static variable. Datetimeformatter class provides many predefined formatters, and you can also customize the format you want. Of course, according to Convention, it also has a parse () method to convert a string into a date. If there is any error during the conversion, it will throw a datetimeparseexception exception. Similarly, the dateformatter class also has a format () method for formatting dates. If it makes an error, it will throw a datetimeexception. 10. Besides, "MMM D yyyy" and "MMM DD yyyy" also have slightly different date formats. The former can recognize the two strings of "Jan 2 2014" and "Jan 14 2014", while the latter will report an error if "Jan 2 2014" is passed in, because it expects two characters to be passed in the month. In order to solve this problem, when the day is a single digit, you have to fill 0 in the front. For example, "Jan 2 2014" should be changed to "Jan 02 2014". That's all about the new time and date API Java 8. These short examples are enough to understand some of the new classes in the new API. Because it is explained based on the actual task, you don't have to look around when you encounter the work of processing time and date in Java later. We learned how to create and modify date instances. We also learned about the difference between pure date, date plus time and date plus time area. We know how to compare two dates and how to find the number of days from a day to a specified 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 using thread local variables or third-party libraries. The new API is competent for any task related to time and date.