20 usage examples of the new time-date library for Java 8

Source: Internet
Author: User
Tags add days date1 days in month time zones local time new set stream api 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

In addition to lambda expressions, stream, and a few minor improvements, Java 8 introduces a new set of time-date APIs that we will use in this tutorial to learn how to work with this set of APIs in Java 8 with a few simple task examples. Java's handling of dates, calendars, and time has been a long-maligned process, especially since it has decided to define java.util.Date as modifiable and to implement SimpleDateFormat as non-thread-safe. It seems that Java is aware of the need to provide better support for time and date features, which is good for communities that are accustomed to using the Joda time and date library. The biggest advantage about this new time and date library is that it defines some concepts related to time and date, such as instantaneous time (Instant), duration (duration), date (time), TimeZone (Time-zone) and time period (Period). It also draws on some of the advantages of the Joda library, such as separating people and machines from the understanding of time and date. Java 8 still has the ISO calendar system, and unlike its predecessors, the classes in the Java.time package are immutable and thread-safe. The new time and date API is in the Java.time package, and here are some of the key classes inside:

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.

The new library also adds Zoneoffset and zoned to provide better support for time zones. The resolution and formatting of the date after the new DateTimeFormatter has become more and more refreshed. Incidentally, I was writing this article when Java was about to launch this new feature at this time last year, so you'll find that the time in the example is still last year. You run these examples and the values they return are definitely correct.

How Java 8 handles time and date

Someone asked me what is the best way to learn a new library? My answer is to use it in the actual project. There will be a variety of requirements in a real project, which will prompt the developer to explore and study the new library. In short, only the task itself will really motivate you to explore and learn. The new date and time API for Java 8 is the same. To learn about this new library for Java 8, I've created 20 task-oriented examples here. Let's start with a simple task, such as how to use the Java 8 time and date library to represent today, and then build a full date with a time zone, and then look at how to do some more practical tasks, such as developing a reminder class application to find out some specific dates such as birthdays, Sunday anniversary, the next account day, the next premium day or the expiration date of the credit card is how many days.

Example 1 how to get the date of the day in Java 8

Java 8 has a class called localdate, which 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. Therefore, if you only need to represent a date and not include time, you can use it.

Localdate today = Localdate.now (); System.out.println ("Today ' s Local Date:" + today);

Output

Today ' s Local date:2014-01-14

You can see that it created today's date without including time information. It also formats the date and then outputs it, unlike the previous date class, where the printed data is unformatted.

Example 2 How to get the current month and date in Java 8

The Localdate class provides some handy ways to extract date attributes from month to day and other dates. Using these methods, you can get to any of the date attributes you need, and no longer need to use classes like Java.util.Calendar:

Localdate today = Localdate.now ();

int year = Today.getyear ();

int month = Today.getmonthvalue ();

int day = Today.getdayofmonth ();

System.out.printf ("Year:%d Month:%d day:%d \ t%n", year, month, day);

Output

Today ' s Local date:2014-01-14

year:2014 month:1 day:14

As you can see, getting the year and year information in Java 8 is very simple, just use the corresponding getter method just fine, no memory, very intuitive. You can compare it to the old one in Java to get the current month and date.

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 day date by using the static method now (), but with another very useful factory method Localdate.of (), you can create any date that accepts the parameter of the month and day. Then an equivalent localdate instance is returned. The good news about this method is that it didn't make any mistakes in the API before, say, the year only starts 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 the January 14, there is no hidden logic.

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

As you can see, the date created is what we wrote, January 14, 2014.

Example 4 How to check if two dates are equal in Java 8

When it comes to the actual task of dealing with time and date, it is common to check that two dates are equal. You may often come across to determine if today is a special day, such as birthdays, anniversaries, or vacations. Sometimes, it will give you a date to let you check if it is not a certain day, say holiday. The following example will help you accomplish this task in Java 8. As you can imagine, Localdate overrides the Equals method to make a date comparison, as follows:

Localdate date1 = Localdate.of (2014, 01, 14); if (Date1.equals (today)) {

System.out.printf ("Today%s and Date1%s is same date%n", today, date1);

}


Output

Today 2014-01-14 and Date1 2014-01-14 is same date

In this example, the two dates we compare are equal. Also, if you get a formatted date string in your code, you have to parse it into a date before you can compare it. You can compare this example to the previous comparison of the dates in Java, and you'll find it really cool.

Example 5 How to check for recurring events in Java 8, such as birthdays

In Java there is also a time date related to the actual task is to check recurring events, such as the monthly account day, wedding anniversary, monthly repayment date or annual payment of insurance premiums. If you work for an e-commerce company, then there will surely be a module that will send a birthday greeting to the user and greet them on every important holiday, such as Christmas, Thanksgiving, and perhaps the festival of Lights in India (Deepawali). How can I tell if it's a holiday or a recurring event in Java? Use the MonthDay class. This class consists of a month-by-day combination that does not contain annual information, which means that you can use it to represent some of the recurring days of the year. There are, of course, some other combinations, such as the Yearmonth class. It is as immutable and thread-safe as any other class in the new time-date library, and it is also a value class. Let's look at an example of how to use MonthDay to check a repeating date:

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!!

Although the year is different, but today is the day of the birthday, so in the output there you will see a birthday blessing. You can adjust the time of the system and then run the program to see if it reminds you when the next birthday is, and you can try to write a junit unit test with your next birthday to see if the code works 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 are using a class called localtime, it is no date time, and Localdate is a close relative. Here you can also use the static Factory method now () to get the current time. The default format is hh:mm:ss:nnn, where the nnn is nanoseconds. You can compare this with how Java 8 gets the current time before.

LocalTime time = Localtime.now (); System.out.println ("local time Now:" + time);


Output

local time now:16:33:33.369//In hour, minutes, seconds, nano seconds

As you can see, the current time is not included in the date, because LocalTime only has time and no date.

Example 7 How to increase the number of hours in a time

Many times we need to increase the hours, minutes or seconds to calculate the future time. Java 8 not only provides immutable and thread-safe classes, it 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, so don't forget to store the new reference.

LocalTime time = Localtime.now ();

LocalTime newtime = time.plushours (2); Adding hours

System.out.println ("Time after 2 hours:" + newtime);


Output:

Time after 2 hours:18:33:33.369

You can see that the current time is 16:33:33.369 after 2 hours. Now you can compare it to the old way of adding or reducing hours in Java. It is better to know which way to look at.

Example 8 how to get the date after 1 weeks

This is similar to the previous example of getting 2 hours of time, where we will learn how to get to the date after 1 weeks. Localdate is used to denote a time-free date, and it has a plus () method that can be used to increase the day, week, or month, and chronounit is used to denote this unit of time. Since Localdate is also immutable, any modifications will return a new instance, so don't forget to save them.

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-14

Date after 1 week:2014-01-21

You can see that 7 days is also a week after the date is what. You can use this method to add one months, a year, an hour, a minute, or even ten years, and look at the Chronounit class in the Java API for more options.

Example date before and after 91 years

This is the sequel to the last example. In the example above, we learned how to use the Localdate Plus () method to add days, weeks, or months to a date, and now let's learn how to use the minus () method to find out what day it was 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-14

Date after 1 year:2015-01-14

It can be seen that there are now altogether two years, one is 2013, the other is 2015, respectively, the year before and after 2014.

Example 10 using clocks in Java 8

Java 8 comes with a clock class that you can use to get the current instantaneous time, date, or time in a time zone. You can use clock to replace the System.currenttimeinmillis () and Timezone.getdefault () methods.

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 zone clock Defaultclock =

Clock.systemdefaultzone ();

System.out.println ("clock:" + clock);


Output:

CLOCK:SYSTEMCLOCK[Z]

CLOCK:SYSTEMCLOCK[Z]

You can compare this clock with the specified date, such as the following:

public class MyClass {

private clock clock; Dependency inject ...


public void process (Localdate eventdate) {


if (Eventdate.isbefore (Localdate.now (clock)) {

...

}

}

}

This is quite handy if you need to deal with dates in different time zones.

Example 11 in Java How to tell if a date is before or after another date

This is also a common task in the actual project. How do you tell if a date is before or after another date, or just equal? In Java 8, the Localdate class has a isbefore () and Isafter () method that can be used to compare two dates. The Isbefore () method returns True if the date of the calling method is earlier than the given date.

Localdate tomorrow = Localdate.of (2014, 1, 15); , 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 today

Yesterday is day before today

You can see that date comparisons in Java 8 are fairly straightforward. There is no need to use another class like the calendar to accomplish a similar task.

Example 12 working with different time zones in Java 8

Java 8 not only separates the date and time, but also the time zone. There are now several groups of time zone-related classes, such as Zonid for a specific time zone, and zoneddatetime for time zones. It is equivalent to the GregorianCalendar class before Java 8. Using this class, you can convert the local time to the corresponding time in another time zone, such as the following example:

Date and time with timezone in Java 8 ZoneID 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]

You can compare it to the previous way to convert the local time to GMT time. By the way, as in Java 8, the corresponding time zone of the text can not be mistaken, otherwise you will encounter such an exception:

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 a credit card expiration time

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

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:31

Your credit card expires on 2018-02

Example 14 How to check leap years in Java 8

This is not complicated, and the Localdate class has a isleapyear () method that returns whether the current localdate corresponds to a leap year. If you still want to make the wheel again, you can look at the code, which is purely Java-written logic to judge whether a year is a leap.

if (Today.isleapyear ()) {

System.out.println ("This was Leap year");

}else {

System.out.println ("A Leap Year");

}


OUTPUT:2014 is isn't a Leap year

You can check more than a few years to see if the results are correct, and you'd better write a unit test to test the normal years and leap year.

Example 152 dates including how many days, how many months

Another common task is to calculate the number of days, weeks, or years between two given dates. You can use the Java.time.Period class to complete this function. In the following example, we will calculate the current date with a total of several months before a future date.

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, this month is January, and the release date for Java 8 is March, so the middle is 2 months apart.

Example 16 date and time with time zone offset

In Java 8, you can use the Zoneoffset class to represent a time zone, for example, if India is GMT or utc5:30, you can use its static method Zoneoffset.of () method to obtain the corresponding time zone. As soon as you get this offset, you can create a offsetdatetime with LocalDateTime and this offset.

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:

Date and time with timezone offset in java:2014-01-14t19:30+05:30

You can see that the current time date is associated with the time zone. Another point is that offsetdatetime is mainly for the machine 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 () can return 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

As you can see, the current timestamp contains the date and time, which is similar to java.util.Date, in fact Instant is the date before Java 8, and you can use the methods in these two classes to convert between the two types, such as Date.from (Instant) is used to convert instant to Java.util.Date, and date.toinstant () converts date to instant.

Example 18 How to use a pre-defined formatter in Java 8 to parse/format dates

Before Java 8, the format of time and date is a technical work, our good partner SimpleDateFormat is not thread-safe, and if used as a local variable to format it is a bit cumbersome. Thanks to thread-local variables, this makes it useful in a multithreaded environment, but Java has maintained that state for a long time. This time it introduces a new thread-safe date-and-time formatter. It also comes with some pre-defined formats, including the usual date formats. For example, in this example we use the predefined basicisodate format, which formats the February 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:

Date generated from String 20140116 is 2014-01-16

You can see that the generated date matches the value of the specified string, which is slightly different on the date format.

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

In the example above, we used the built-in time date formatter to parse the date string. Of course, the pre-defined format is good, but sometimes you might want to use a custom date format, and you'll have to create a custom date formatter instance yourself. The date format in the following example is "MMM 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 still represents the month, and M is still the point. An invalid pattern throws a Datetimeparseexception exception, but if it is a logical error such as using M, it will not work.

String Goodfriday = "APR 18 2014";

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

You can see that the value of the date is exactly the same as the passed-in string, except for the format.

Example 20 how to format dates in Java 8 and convert them to strings

In the last two examples, although we have used the DateTimeFormatter class, we are mainly parsing date strings. What we're going to do in this case is just the opposite. Here we have an instance of the LocalDateTime class, and we want to convert it into a well-formed date string. This is by far the simplest and easiest way to convert dates into strings in Java. The following example will return a well-formed string. As in the preceding example, we still need to use the specified pattern string to create an instance of the DateTimeFormatter class, but not the parse method of the Localdate class, but its format () method. This method returns a string representing the current date, and the corresponding pattern is defined in the incoming DateTimeFormatter instance.

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

As you can see, the current time is expressed in the given "MMM DD yyyy hh:mm a" pattern, which contains three letters of the month and the time expressed in am and PM.

Several key points in the 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 for Java 8. Now let's review some of the key elements of this new API.

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 2014-01-14t02: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 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 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. Since it is based on actual tasks, it is not necessary to look around again when you encounter the task of working with time and date in Java. 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.

If you are also interested in Java 8 tutorials, take a look at these tutorials:

How can I read a file in Java 8 with a single line of code? Example

Learn Java 8 to read 10 tutorials (tutorial)

Free Java 8 Tutorials and books (resources)

Java 8 Comparator Use example (example)

How to use the map function in Java 8 (example)

Ready for Java 8 certification (more)

How to use the default method in Java 8 (example)

Learn about the 10 Java 7 features that should be reviewed before Java 8 (more)

Example of using the Stream API in Java 8 (example

How to use a lambda expression instead of an anonymous class (solution)

How to use predicate in Java 8 to filter collections (solutions)

How do I read Randomaccessfile in Java? (solution)

20 usage examples of the new time-date library for Java 8

Related Article

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.