Java 8 new Time Date Library's 20 use examples _java

Source: Internet
Author: User
Tags add days date1 days in month time zones local time new set stream api time and date

Original: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 and date APIs, and in this tutorial we will learn how to use this set of Java 8 APIs with a few simple task examples. Java's handling of dates, calendars, and time has been a constant complaint, especially as it decides to define java.util.Date as modifiable and to implement SimpleDateFormat as not thread-safe. It seems that Java has realized the need to provide better support for time and date functions, which is good for communities that are accustomed to using Joda time and date libraries. The great advantage of this new time and date library is that it defines some concepts related to time and date, for example, instantaneous time (Instant), duration (duration), date, time, The time zone (Time-zone) and the period (Period). It also draws on some of the advantages of the Joda library, such as separating the people from the machine's understanding of the time and date. Java 8 still has the ISO calendar system, and unlike its predecessors, classes in the Java.time package are immutable and thread-safe. The new time and date APIs are located in the Java.time package, and below are some of the key classes inside:

    • 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.

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

How Java 8 handles time and date

I was asked what is the best way to learn a new library? My answer is to use it in the actual project. There are a variety of requirements in a real project that will encourage developers 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 of Java 8, here I have created 20 task-oriented examples. Let's start with a simple task, for example, how to use the Java 8 time and date library to represent today, and then further generate a time zone with a full date, and then study how to complete some more practical tasks, such as the development of a reminder class application to find out some specific dates such as birthdays, Sunday anniversary, next day, next premium or credit card expiration date.

Example 1 how to get the day's date 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. So, if you only need to represent a date but not a 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 the time information. It also formats the date and then prints it out, unlike the previous date class, where the printed data is unformatted.

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

The Localdate class provides a convenient way to extract the date and time attributes of the month and the year. Using these methods, you can get any date attribute you need, and you no longer need to use a class 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 

You can see that in Java 8 to get the month information is very simple, just use the corresponding Getter method is good, no memory, very intuitive. You can compare it to the old Java way of getting the current month and year.

Example 3 How to get a specific date in Java 8

In the first example, we see a static method now () to generate today's date is very simple, but through another very useful factory method Localdate.of (), you can create any date, it accept the parameters of the date of year, An equivalent localdate instance is then returned. The good news about this approach is that it didn't make the same mistake in the API before, for example, only starting from 1900, the month must start at 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 (a); 
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

If you talk about real time and date tasks in reality, it is common to check whether two dates are equal. You may often have to decide if today is a special day, such as birthdays, anniversaries, or vacations. Sometimes, you will be given a date to check whether it is a day, for example, a holiday. Here's an example that will help you complete this task in Java 8. As you can imagine, localdate rewrites the Equals method to compare dates, as follows:

Localdate date1 = Localdate.of (2014, 01, 14); if (date1.equals) { 
  System.out.printf ("Today%s and Date1%s are same date%n", today, date1); 
 
Output today 
2014-01-14 and date1 2014-01-14 are same date

In this case, 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 way Java compared the dates before, and you'll find that it's a lot more fun.

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

In Java there is also a time and date related to the actual task is to check the recurrence of events, such as the monthly billing day, wedding anniversary, monthly repayment date or the date of the annual insurance premiums. If you work for a power company, there will be a module that will send a birthday greeting to users and greet them on every important holiday, such as Christmas, Thanksgiving, or Deepawali in India. 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-day combination that contains no annual information, which means that you can use it to represent the recurring days of the year. Of course there are other combinations, such as the Yearmonth class. It is as immutable and thread-safe as the other classes in the new Time Date library, and it is also a value class. Let's look at how to use MonthDay to check for a duplicate date by using an example:

Localdate dateOfBirth = Localdate.of (a); 
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," "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 you will see a birthday blessing. You can adjust the system time to run this program to see if it can remind you when your next birthday is, and you can also 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 not a 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 nanosecond. Can compare with Java 8 How to get 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 does not contain a date, because localtime only time, no date.

Example 7 How to increase the number of hours in time

Many times we need to increase the hours, minutes or seconds to calculate the future time. Not only does Java 8 provide immutable and thread-safe classes, it also provides more convenient methods such as plushours () to replace the original add () method. Incidentally, these methods return a reference to a new localtime instance, because LocalTime is immutable, and don't forget to store this new reference.

LocalTime time = Localtime.now (); 
LocalTime newtime = time.plushours (2); Adding two hours 
System.out.println ("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 2 hours later. Now you can compare it to the old ways of adding or reducing hours in Java. It's better to know which way to look.

Example 8 how to obtain a date 1 weeks later

This is similar to the previous example of getting a 2-hour time, where we will learn how to get to the date 1 weeks later. Localdate is used to indicate a date without time, and it has a plus () method that can be used to increase the day, week, or month, and Chronounit is used to represent this time unit. Since Localdate is also immutable, any modification operation will return a new instance, so don't forget to save it.

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

You can see what the date of 7 days is a week later. You can use this method to add one months, a year, an hour, a minute, or even ten years, to view the Chronounit class in the Java API to get more options.

Example 91 years before and after the date

This is the sequel to the previous example. In the example above, we learned how to use the Localdate Plus () method to add days, weeks or months to the date, and now we're going to learn how to use the minus () method to find the day of the year.

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 two years, one is 2013, one is 2015, respectively, the year before and after 2014.

Example 10 using the clock 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 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 a 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 how to determine whether a date is before or after another date in Java

This is also a common task in the actual project. How do you decide if a date is in front of another date or is it just the same? 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 call method is earlier than the given date.

Localdate tomorrow = Localdate.of (2014, 1, 15); , if (Tommorow.isafter (today)) { 
  System.out.println ("Tomorrow Comes on Today"); 
} 
Localdate yesterday = Today.minus (1, days); 
if (Yesterday.isbefore (today)) { 
  System.out.println ("Yesterday are day before today"); 
 
Output: 
tomorrow comes after today 
yesterday be day before today

You can see that the date comparison in Java 8 is very simple. There is no need to use another class like calendar to accomplish a similar task.

Example 12 handles different time zones in Java 8

Java 8 not only separates dates and times, but also time zones. There are now several groups of time zone-related classes, such as Zonid represents a particular time zone, and Zoneddatetime represents time with a time zone. It is equivalent to the GregorianCalendar class before Java 8. With 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 with the way you converted the local time to GMT time. By the way, as in Java 8, the text in the corresponding time zone is not mistaken, otherwise you will encounter 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)
    

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 a credit card repayment date, a term deposit maturity, and a options maturity. You can use this class to find out how many days of the month, Lengthofmonth () This method returns the Yearmonth instance how many days, this is very useful for checking whether February is 28 days or 29 days.

Yearmonth currentyearmonth = Yearmonth.now (); System.out.printf ("Days in month year%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 year 2014-01:31 
Your, expires on 2018-02  

Example 14 How to check a leap year in Java 8

This is nothing complicated, and the Localdate class has a isleapyear () method that returns whether the current localdate corresponds to a leap year. If you want to repeat the wheel, you can look at this code, which is a purely Java-written logic to determine whether a year is leap years.

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

You can check for a few more years to see if the results are correct, and it's best to write a unit test to test the normal years and leap year.

Example 152 date contains how many days, how many months

Another common task is to calculate how many days, weeks, or years are included between the two given dates. You can use the Java.time.Period class to perform this function. In the following example, we will calculate the current date and a future date to be separated by a few months.

Localdate java8release = Localdate.of (2014, Month.march,); 
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 Java 8 release date is March, so the middle is 2 months.

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 get 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 (2014, month.january, M,); 
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 now that the time date is associated with a 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 value of this instant" + timestamp); 
 
Output: 
What is value to this instant 2014-01-14t08:33:33.379z

As you can see, the current timestamp contains date and time, 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 parse/format a date using a predefined formatter in Java 8

Before Java 8, the format of the time date was a technical activity, and our good partner SimpleDateFormat was not thread-safe, and it was cumbersome to format it as a local variable. Thanks to the thread-local variables, this makes it useful in a multithreaded environment, but Java has been there for a long time. This time it introduces a new thread-safe date and time formatter. It also brings in some predefined 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 is%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 a slightly different date format.

Example 19 How to use a custom formatter in Java to resolve dates

In the example above, we used the built-in time date formatter to parse the date string. Of course, the predefined format is really 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 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 still represents the month, and M is still divided. An invalid pattern throws a Datetimeparseexception exception, but if it is a logical error, such as using M, then there is no way.

String Goodfriday = "Apr 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 2014, date is 2014-04-18

You can see that the value of the date matches the passed-in string, but the format is different.

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

In the last two examples, although we used the DateTimeFormatter class, we were mainly parsing the date strings. In this case we're going to do exactly the opposite thing. Here we have an instance of the LocalDateTime class that we want to convert into a formatted date string. This is the simplest and easiest way to translate dates into strings in Java so far. The following example returns a formatted string. As in the previous 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 DateTimeFormatter instance that is passed in.

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 2014 04:33 PM

As you can see, the current time is represented by the given "MMM DD yyyy hh:mm a" pattern, which contains the three-letter month and the time represented by AM and PM.

Several key points of the date and time API in Java 8

After reading these examples, I believe you have a certain understanding of the Java 8 new time and date API. Now let's review some of the key elements of this new API.

  1. It provides javax.time.ZoneId for processing time zones.
  2. It provides the localdate and LocalTime classes
  3. 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.
  4. 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.
  5. 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 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, 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
  6. 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.

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

  8. 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).

  9. 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.

  10. 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. Because it is based on the actual task to explain, so later encountered in Java to deal with the time and date of work, there is no need to look around. 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.

If you are also interested in the Java 8 tutorial, take a look at the following tutorials:

    • How can I read a file in Java 8 with one line of code? Example
    • Learn Java 8 to read 10 Tutorials (tutorials)
    • Free Java 8 Tutorials and books (resources)
    • Comparator use example for Java 8 (sample)
    • How to use the map function in Java 8 (sample)
    • Are you ready for Java 8 certification (more)
    • How to use the default method in Java 8 (sample)
    • Learn about the 10 Java 7 features that should be reviewed before Java 8 (more)
    • Example of using the Stream API in Java 8 (sample)
    • How to use lambda expressions instead of anonymous classes (solution)
    • How to filter the collection using predicate in Java 8 (solution)
    • How do I read Randomaccessfile in Java? (solution)

English text link

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.