Java 8 time and date API 20 examples

Source: Internet
Author: User
Tags date1 days in month time zones local time time and date

With lambda expressions, streams, and a series of small optimizations, Java 8 introduces a new DateTime API, and in the tutorial we'll learn how to use the new API with some simple examples. The way that Java handles dates, calendars, and Times has been criticized by the community, setting Java.util.Date to mutable types, and SimpleDateFormat's non-thread-safe application is very limited. Java is also aware of the need for a better API to meet people in the community who are accustomed to using the Jodatime API. One of the many benefits of the new API is the definition of datetime concepts such as instantaneous (instant), Length (duration), date, time, time zone, and period. At the same time, inherit the Joda library according to the human language and the computer to parse the temporal processing mode. Unlike the old version, the new API is based on the ISO Standard calendar system, and all classes under the Java.time package are immutable types and thread-safe. Here are some of the key classes in the Java.time package in the new API:

    • Instant: instantaneous instance.
    • Localdate: Local date, not specific time for example: 2014-01-14 can be used to record birthdays, anniversaries, joining days and so on.
    • LocalTime: local time, not including date.
    • LocalDateTime: Combines date and time, but does not contain slack and time zone information.
    • Zoneddatetime: The most complete datetime, including time zone and time difference from UTC or Greenwich.

The new API also introduces the Zoneoffset and ZoneID classes, making it easier to solve time zone problems. The DateTimeFormatter classes that parse and format time are all redesigned. Note that This article was written by me a year ago when Java 8 was about to be released, and the following sample code is the time of year, and when you run these examples, you will return your current time.

How to handle dates and times in Java 8

People often ask me what is the best way to learn a new library? My answer is to use it in the actual project. There are many real needs in the project that drive developers to explore and learn new libraries. Simply put, task-driven learning explores. This is no exception to the Java 8 new DateTime API. I created 20 task-based instances to learn the new features of Java 8. Start with the date of the simplest creation day, then create a time zone, and then simulate a task in a date reminder app--Calculate the expiration days for important dates, such as birthdays, anniversaries, billing days, premiums due dates, credit card expiry dates, and so on.

Example 1, getting today's date in Java 8

Localdate in Java 8 is used to represent today's date. Unlike Java.util.Date, it has only dates and no time. Use this class when you only need to represent a date.

Localdate today = Localdate.now (); System.out.println ("Today ' s Local Date:" + today);
Outputtoday ' s Local date:2014-01-14

The above code creates the date of the day without the time information. The printed date format is very friendly and does not print out a bunch of unformatted information like the old date class.

Example 2, getting the year, month, and day information in Java 8

The Localdate class provides a quick way to get the year, month, and day, and its instances contain many other date attributes. By invoking these methods, it is convenient to get the required date information, instead of relying on the Java.util.Calendar class as before.

Localdate today = Localdate.now (), int year = Today.getyear (), int month = Today.getmonthvalue (); Int day = Today.getdayofmon Th (); System.out.printf ("Year:%d  month:%d day  :%d T%n", year, Month, day);
Outputtoday ' s Local date:2014-01-14year:2014  month:1  day:14

See, in Java 8 to get the year, month, day information is so simple and intuitive, want to use, there is nothing to remember. Look at how Java has been dealing with the month and day information.

Example 3, working with a specific date in Java 8

In the first example, we created the day date very easily by using the static Factory method now (), and you can call another useful factory method Localdate.of () to create any date, which requires passing in the year, month, and day parameters to return the corresponding Localdate instance. The advantage of this method is that the design error of the old API is not repeated, such as the year starting at 1900, the month starting from 0 and so on. The date is WYSIWYG, as shown in the following example, January 14, without any hidden organs.

Localdate dateOfBirth = Localdate.of (2010, 01, 14); System.out.println ("Your Date of Birth is:" + dateOfBirth);
Output:your Date of birth is:2010-01-14

You can see that the created date is exactly what you expected, exactly as you wrote January 14, 2010.

Example 4, determining whether two dates are equal in Java 8

A class of time in real life is to determine whether two dates are equal. You will often check that today is not a special day, such as birthdays, anniversaries or non-trading days. You need to compare the specified date with a specific date, for example, to determine whether the day is a holiday. The following example will help you in the way of Java 8 to solve, you must have thought, localdate overloaded the equal method, see the following example:

Localdate date1 = Localdate.of (n, +), if (Date1.equals (today)) {    System.out.printf ("Today%s and Date1%s is SA Me date%n ", today, Date1);}
Outputtoday 2014-01-14 and Date1 2014-01-14 is same date

In this example we compare the same two dates. Note that if the date of the comparison is of character type, it needs to be parsed into a date object before being judged. Compare the old Java date comparison style and you'll feel the breeze blowing.

Example 5, checking for recurring events like birthdays in Java 8

Another datetime in Java is the process of checking for recurring events such as monthly bills, wedding anniversaries, EMI days, or insurance payment days. If you work on an e-commerce site, there must be a module to send greeting messages to customers on Christmas and Thanksgiving holidays. How do you check these festivals or other recurring events in Java? The answer is the MonthDay class. This class combines the month and day, minus the year, which means that you can use it to judge the events that occur every year. Similar to this class, there is a Yearmonth class. These classes are also immutable and thread-safe value types. Below we examine the recurring events through MonthDay:

Localdate dateOfBirth = Localdate.of (2010, 01, 14); MonthDay birthday = Monthday.of (Dateofbirth.getmonth (), Dateofbirth.getdayofmonth ()); MonthDay Currentmonthday = Monthday.from (today); if (Currentmonthday.equals (birthday)) {   System.out.println ("Many many happy returns of the Day");} else{   System.out.println ("Sorry, today is not your Birthday");}
Output:many Many happy returns of the day!!

As long as the day's date and birthday match, no matter which year will print out the congratulations message. You can integrate the program into the system clock to see if your birthday is being alerted, or write a unit test to check that your code is running correctly.

Example 6, getting the current time in Java 8

Like the Java 8 get date example, the acquisition time is using the LocalTime class, a localdate close relative who has only time without dates. You can call the static factory method now () to get the current time. The default format is hh:mm:ss:nnn. Compare the way you get the current time before Java 8.

LocalTime time = Localtime.now (); System.out.println ("local time Now:" + time);
Outputlocal time now:16:33:33.369  //In hour, minutes, seconds, nano seconds

You can see that the current time contains only time information and no date.

Example 7, how to add an hour to an existing time

It is common to calculate the future time by adding hours, minutes, seconds. Java 8, in addition to the invariant type and thread-safe benefits, provides a better plushours () method to replace add () and is compatible. Note that these methods return a completely new localtime instance, and because of its immutability, it is important to assign a value to the variable after it returns.

LocalTime time = Localtime.now (); LocalTime newtime = time.plushours (2); Adding-hoursSystem.out.println ("Time after 2 hours:" +  newtime);
Output:time after 2 hours:18:33:33.369

As you can see, the new time is increased by 2 hours on the basis of the current time 16:33:33.369. And the old version of the Java change the time to deal with the way to see which kind of better.

Example 8, how to calculate the date after one week

Similar to the last example calculated two hours later, this example calculates the date one week later. The localdate date does not contain time information, and its plus () method is used to increase days, weeks, and months, and the Chronounit class declares these units of time. Since Localdate is also invariant, be sure to assign a value to the variable after returning.

Localdate Nextweek = Today.plus (1, chronounit.weeks); System.out.println ("Today is:" + today); System.out.println ("Date after 1 week:" + Nextweek);
Output:today is:2014-01-14date after 1 week:2014-01-21

You can see that the new date is 7 days from today, that is, a week. You can add 1 months, 1 years, 1 hours, 1 minutes, or even a century in the same way, more options to view the Chronounit class in the Java 8 API.

Example 9, calculating a date a year ago or a year later

Continuing with the example above, we used the Localdate Plus () method to increase the number of days, weeks, or months in the previous example, and we use the minus () method to calculate the date a year ago.

Localdate previousyear = Today.minus (1, chronounit.years); System.out.println ("Date before 1 year:" + previousyear); Localdate nextyear = Today.plus (1, years); System.out.println ("Date after 1 year:" + nextyear);
Output:date before 1 year:2013-01-14date after 1 year:2015-01-14

The results of the example were two dates, one 2013 years, one 2015 year, respectively, the previous year and the following year in 2014.

Example 10, clock clock class using Java 8

Java 8 adds one clock clock class to get the timestamp at the time, or the datetime information in the current time zone. The previous use of System.currenttimeinmillis () and Timezone.getdefault () can be replaced by clock.

Returns the current time based on your system clock and set to UTC. Clock Clock = CLOCK.SYSTEMUTC (); System.out.println ("clock:" + clock); Returns time based on system clock Zoneclock defaultclock = Clock.systemdefaultzone (); System.out.println ("clock:" + clock);
OUTPUT:CLOCK:SYSTEMCLOCK[Z]CLOCK:SYSTEMCLOCK[Z]
You can also make comparisons for clock clocks, as in the following example:
public class MyClass {    private clock clock;  Dependency inject ...    public void process (Localdate eventdate) {      if (Eventdate.isbefore (Localdate.now (clock)) {        ...      }}}    

This works well when working with dates in different time zones.

Example 11, how to use Java to determine whether a date is earlier than or later than another date

Another common operation is how to tell if a given date is greater than one day or less than one day? In Java 8, the Localdate class has two classes of methods Isbefore () and Isafter () for comparing dates. Returns true if the given date is less than the current date when the Isbefore () method is called.

Localdate tomorrow = Localdate.of (1, +), if (Tommorow.isafter (today)) {    System.out.println ("Tomorrow Comes After today "); Localdate yesterday = Today.minus (1, days); if (Yesterday.isbefore (today)) {    System.out.println ("Yesterday is day before today");
Output:tomorrow comes after Todayyesterday are day before today

It is convenient to compare dates in Java 8 without the need for additional calendar classes to do the basic work.

Example 12, working with time zones in Java 8

Java 8 not only separates the date and time, but also separates the time zone. There are now a series of separate classes such as ZoneID to handle a specific time zone, Zonedatetime class to represent time in a time zone. This was done by the GregorianCalendar class before Java 8. The following example shows how to convert time in this time zone to another time zone.

Date and time with timezone in Java 8ZoneId america = Zoneid.of ("America/new_york"); LocalDateTime localtdateandtime = Localdatetime.now (); Zoneddatetime dateandtimeinnewyork  = Zoneddatetime.of (Localtdateandtime, America); System.out.println ("Current date and time in a particular timezone:" + dateandtimeinnewyork);
Output:current date and time in a particular timezone:2014-01-14t16:33:33.373-05:00[america/new_york]
Compare the local time with the previously used GMT method. Note that before Java 8, be sure to remember the name of the time zone, otherwise the following exception will be thrown:
Exception in thread "main" Java.time.zone.ZoneRulesException:Unknown Time-zone Id:asia/tokyo at        Java.time.zone.ZoneRulesProvider.getProvider (zonerulesprovider.java:272) at        Java.time.zone.ZoneRulesProvider.getRules (zonerulesprovider.java:227) at        java.time.ZoneRegion.ofId ( zoneregion.java:120) at        Java.time.ZoneId.of (zoneid.java:403) at        java.time.ZoneId.of (zoneid.java:351)
Example 13, how to indicate a fixed date such as credit card expiry, the answer is Yearmonth

Similar to the example of monthday checking for duplicate events, Yearmonth is another combination class that represents the credit card expiry date, FD expiry date, futures option expiry date, and so on. You can also use this class to get the number of days in a month, the Lengthofmonth () method of the Yearmonth instance can return the number of days of the month, which is useful when judging whether there are 28 or 29 days in February.

Yearmonth currentyearmonth = Yearmonth.now (); System.out.printf ("Days in Month"%s:%d%n ", Currentyearmonth, Currentyearmonth.lengthofmonth ()); Yearmonth Creditcardexpiry = yearmonth.of (2018, Month.february); System.out.printf ("Your credit card expires on%s%n", Creditcardexpiry);
Output:days in month 2014-01:31your credits card expires on 2018-02

Based on the above data, you can remind customers that the credit card is about to expire and that the class is very useful.

Example 14, how to check a leap year in Java 8

Localdate class has a very useful method isleapyear () to determine if the instance is a leap year, if you still want to reinvent the wheel, this has a code example, pure Java logic written to judge a leap year program.

if (Today.isleapyear ()) {   System.out.println ("This year is a Leap year");} else {    System.out.println ("a Leap Year");}
OUTPUT:2014 is isn't a Leap year

You can write more than a few dates to verify whether it is a leap year, preferably by writing JUnit unit tests.

Example 15, calculating the number of days and months between two dates

One common date operation is to calculate the number of days, weeks, or months between two dates. In Java 8, you can use the Java.time.Period class to do the calculations. In the following example, we calculate the number of months between the day and the Future Day.

Localdate java8release = Localdate.of (Month.march, 14); Period periodtonextjavarelease = Period.between (today, java8release); System.out.println ("Months left between today and Java 8 release:"                                   + periodtonextjavarelease.getmonths ());
Output:months left between today and Java 8 Release:2

As you can see from the above, it is January, and the release date for Java 8 is March, which is two months apart.

Example 16, date and time with slack information

In Java 8, the Zoneoffset class is used to represent time zones, for example, if India differs from the GMT or UTC standard Time zone +05:30, the corresponding time zone can be obtained through the Zoneoffset.of () static method. Once you get the time difference, you can create a Offsetdatetime object by passing in LocalDateTime and Zoneoffset.

LocalDateTime datetime = Localdatetime.of (Month.january, 14, 19, 30); Zoneoffset offset = zoneoffset.of ("+05:30"); Offsetdatetime date = Offsetdatetime.of (datetime, offset);  System.out.println ("Date and time with timezone offset in Java:" + date);
Output:D ate and time with timezone offset in java:2014-01-14t19:30+05:30

Time zone information has been included in the current information. Note: Offsetdatetime is computer-friendly, and zonedatetime is more friendly to people.

Example 17, getting the current timestamp in Java 8

If you remember how the current timestamp was obtained before Java 8, you are finally relieved. The instant class has a static factory method now () that returns the current timestamp as follows:

Instant timestamp = Instant.now (); System.out.println ("What is the value of this instant" + timestamp);
Output:what is the value of this instant 2014-01-14t08:33:33.379z

The timestamp information contains both the date and time, which is much like the java.util.Date. In fact, the Instant class is indeed equivalent to the date class before Java 8, and you can use the date class and the Instant class to convert each other, for example: Date.from (Instant) Converting instant to Java.util.date,date.toinstant () is the conversion of the Date class to the Instant class.

Example 18, how to use the predefined formatting tools in Java 8 to parse or format dates

In the world before Java 8, the formatting of dates and times is very strange, the only helper class SimpleDateFormat is also non-thread-safe, and used as a local variable parsing and formatting dates is cumbersome. Fortunately, thread-local variables make it usable in a multithreaded environment, but this is the past. Java 8 introduces a new date-time format tool that is thread-safe and easy to use. It comes with some of the most common built-in formatting tools. The following example uses the Basic_iso_date format tool to format the January 14, 2014 as 20140114.

String Dayaftertommorrow = "20140116"; Localdate formatted = Localdate.parse (Dayaftertommorrow,                        datetimeformatter.basic_iso_date); System.out.printf ("Date generated from String%s was%s%n",                    Dayaftertommorrow, formatted);
Output:D ate generated from String 20140116 is 2014-01-16

It is obvious that the date and date given are the same day, but the format is different.

Example 19, how to resolve dates in Java using a custom formatting tool

The last example uses a Java built-in formatting tool to parse a date string. Although the built-in formatting tools work well, and sometimes you need to define a specific date format, the following example shows how to create a custom date formatting tool. The date format in the example is "MMM dd yyyy". You can call DateTimeFormatter's Ofpattern () static method and pass in any format to return the example, the characters in the format are the same as the previously represented, M for the month, and M for the minute. A Datetimeparseexception exception is thrown if the format is not canonical, but a logic error such as M is not thrown out of the ordinary.

String goodfriday = "APR"; try {    DateTimeFormatter formatter = Datetimeformatter.ofpattern ("MMM dd yyyy"); 
   
    localdate holiday = Localdate.parse (Goodfriday, formatter);    SYSTEM.OUT.PRINTF ("Successfully parsed String%s, date is%s%n", Goodfriday, Holiday);} catch (Datetimeparseexception ex) {    System.out.printf ("%s is not parsable!%n", goodfriday);    Ex.printstacktrace ();}
   
output:successfully parsed String Apr, date is 2014-04-18

The date value matches the passed-in string, only the format is different.

Example 20, how to convert a date to a string in Java 8

The last two examples all use the DateTimeFormatter class, mainly from the string parsing date. Now we turn to convert the LocalDateTime date instance into a string of a specific format. This is by far the simplest way to date Java dates to strings. The following example returns a formatted string representing the date. Similar to the previous one, you need to create a DateTimeFormatter instance and pass in the format, but this callback calls the format () method, not the parse () method. This method converts the incoming date into a string of the specified format.

LocalDateTime arrivaldate  = Localdatetime.now (); try {    datetimeformatter format = Datetimeformatter.ofpattern ("MMM DD yyyy  hh:mm a");    String landing = arrivaldate.format (format);    System.out.printf ("Arriving at:  %s%n", landing),} catch (Datetimeexception ex) {    System.out.printf ("%s can ' t Be formatted!%n ", arrivaldate);    Ex.printstacktrace ();}
Output:arriving at:  Jan  04:33 PM

The current time is formatted with the specified "MMM DD yyyy hh:mm a" format, which contains 3 strings representing the month, followed by the AM and PM tags.

The focus of the Java 8th time API

With these examples, you must have mastered the new knowledge points of the Java 8th Time API. Now let's review the use points of this elegant API:

1) provides javax.time.ZoneId to get the time zone.

2) Localdate and LocalTime classes are available.

3) All date and time APIs in Java 8 are immutable and thread-safe, while Java.util.Date and SimpleDateFormat in the existing date and calendar APIs are non-thread safe.

4) The main package is Java.time, which contains some classes that represent the date, time, and time interval. There are two sub-packages Java.time.format for formatting, java.time.temporal for the lower-level operation.

5) The time zone represents the standard time that is commonly used in an area on Earth. Each time zone has a code name, which usually consists of a region/city composition (Asia/tokyo), plus a difference in Greenwich or UTC. For example, Tokyo's time difference is +09:00.

6) The Offsetdatetime class actually combines the LocalDateTime class and the Zoneoffset class. Used to represent the full date (year, month, day) and time (hour, minute, second, nanosecond) information that contains the Greenwich or UTC difference.

7) The DateTimeFormatter class is used for formatting and parsing time. Unlike SimpleDateFormat, this class is immutable and thread-safe, and you can assign values to static constants when needed. The DateTimeFormatter class provides a number of built-in formatting tools and also allows you to customize. Parse () is also provided in the transformation to parse the string into a date, and if parsing is an error, it throws datetimeparseexception. The DateTimeFormatter class also has format () for formatting dates and throws a Datetimeexception exception if an error occurs.

8) Add a little, date format "MMM d yyyy" and "MMM dd yyyy" have some subtle differences, the first format can parse "Jan 2 2014" and "Jan 14 2014", while the second in parsing "Jan 2 2014" will throw an exception, The requirement date in the second format must be two bits. If you want to fix it, you must make 0 in front of the date with only one digit, meaning "Jan 2 2014" should be written as "Jan 02 2014".

How to use the new Date Time API for Java 8 is covered here. These simple examples are useful for helping to understand the new API. Since these examples are based on real-world tasks, you don't have to go around looking for Java date programming. We learned how to create and manipulate date instances, learn the dates that are pure dates, and include time information and slack information, and learn how to calculate intervals for two dates, which are shown in the example of the day of calculation and a particular date interval. We also learned how to thread safely parse and format dates in Java 8 without using crappy thread-local-variable techniques or relying on Joda time third-party libraries. The new API can be used as a standard for processing date-time operations.

Java 8 time and date API 20 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.