Original: http://it.Deepinmind.com/java/2015/03/17/20-examples-date-ndate-di-from-java8.html
In addition to Lambda expressions, Stream and several small improvements, Java 8 also introduced a new set of time and date API. In this tutorial, we will learn how to use Java 8 through several simple task examples. Set API. Java's dates, calendars, and time processing have always been criticized, especially it decides to define Java.util.date as modified and use SimpleDateFormat into non -thread security. It seems that Java has realized that it needs to provide better support for the time and date functions, which is also a good thing for the community that is accustomed to using the JODA time database. The biggest advantage of this new time and date library is that it defines some concepts related to time and date. For example, instantaneous time, duration, date, time (time), time zone (time), time zone (Time-Zone) and Period. At the same time, it also borrows some advantages of the JODA library, such as distinguishing between people and machines to distinguish the time date. Java 8 still uses the ISO calendar system, and unlike its predecessors, the classes in the Java.time package are unsusable and thread -safe. The new time and date API is located in the java.time package. Below is some of the key categories inside:
The new library also adds ZoneOffset and ZONED to provide better support for the time zone. With the new DateTimeFormatter, the analysis and formatting of the date after the date have become new. Just mention it, I was writing this article when Java was about to launch this new feature at this time, so you will find that the time in the example is last year. If you run these examples, the values they return must be correct.
Someone asked me what is the best way to learn a new library? My answer is to use it in actual projects. There will be a variety of needs in a real project, which will promote developers to explore and study this new library. In short, only the task itself will really promote you to explore and learn. The new date and time API of Java 8 is the same. In order to learn this new library of Java 8, I created 20 task -oriented examples here. Let's start with a simple task. For example, how to use the time and date library of Java 8 to express today, and then further generate a complete date with a time zone, and then study how to complete some more practical tasks, such as saying that it is said that Develop an application of reminders to find out some specific date such as birthday, Sunday anniversary, the next account date, how many days are there for the next premium date or credit card expiration time.
There is a class called LocalDate in Java 8, which can be used to represent the date of today. This class is slightly different from java.util.date, because it only contains the date and has no time. Therefore, if you only need to indicate the date instead of time, you can use it.
Localdate today = localdate.now (); system.out.println ("TODAY's LOCAL DTE:" + TODAY); Output TODAY's Local Date: 2014-01-14You can see that it creates today but does not include time information. It also forms the date format and outputs it. Unlike the previous Date class, the printed data are not formatted.
The LocalDate class provides some very convenient ways to use the date and other date attributes that can be used to extract. Using these methods, you can get any date attribute you need, and no longer need to use a class such as java.util.Calendar:
LOCALDATE TODAY = LOCALDATE.NOW (); int Year = TODAY.GETYEAR (); int Month = TODAY.GetmonthValue (); int UT.printf ("Year: %D Month: % day: %d /t %n ", year, month, day); Output today's local date: 2014-01-14 year: 2014 MONTH: 1 day: 14It can be seen that it is very simple to obtain the annual information in Java 8. It only needs to use the corresponding Getter method, no memory, very intuitive. You can compare it with the writing of the current month and day in Java.
In the first example, we see that it is very simple to generate the date of the day through the static method, but through another very useful factory method LocalDate.of (), you can create any date. It accepts it accepted The parameters of the year, the month, and then return a equivalent LocalDate instance. Another good news about this method is that it did not make any mistakes in the API before. For example, the year can only start from 1900, the month must start from 0, and so on. What you write here is what you write here, for example, in the following example, it represents January 14, there is no hidden logic.
Localdate dateofbirth = localdate.of (2010, 01, 14); System.out.println ("Your Date of BIRTH is:" + Dateofbns); Output: Your Date of Birth is: 2010-01 -14It can be seen that the date of created is what we write, January 14, 2014.
Speaking of the actual processing time and date tasks in reality, one is common to check whether two dates are equal. You may often encounter whether to judge whether today is a special day, such as birthday, anniversary, or holidays. Sometimes, you will give you a date so that you can check whether it is a certain day. The following example will help you complete such tasks in Java 8. As you think, LocalDate rewritten the Equals method to compare the date, as shown below:
LocalDate date1 = localdate.of (2014, 01, 14); if (date1.equals (today)) {system.out.printf ("today %s and date1 %sme say date %n", today); } Output today 2014-01-14 and date1 2014-01-14 Are Same DateIn this example, our comparison two dates are equal. At the same time, if you get a formatted date string in the code, you have to resolve it as a date before you can compare it. You can compare this example to compare the previously comparison of Java, and you will find that it is much better.
There is also a practical task related to the time date in Java to check duplicate events. For example, the monthly billing day, wedding anniversary, monthly repayment date or annual insurance premiums. If you work in an e -commerce company, then there will be such a module that will send birthday wishes to users and give them greetings on each important holiday, such as Christmas, Thanksgiving, in India, it may be possible in India. It is deepawali. How to determine whether it is a festival or repeated incident in Java? Use the MonthDay class. This category is combined by the month and does not include annual information, which means that you can use it to represent some of the days that appear repeated each year. Of course, there are some other combinations, such as the YearmontH class. It is also unable to change and thread safely as other types in the new time library, and it is also a value class. Let's see how to use MonthDay to check a duplicate date:
LOCALDATE DTEALDAY BIRTHDAY.of (2010, 01, 14); MonthDay Birthday = Monthday.OF (Dateofbirth.GetDayofmonth ()); month Day CurrenTMONTHDAY = MONTHDAY.FROM (TODAY); if (CurrenTMONTHDAY.EQUALS BIRTHDAY) {System.out.println ("Many Many HAPPY RETURNS of the Day !!"); TPUT: Many Many Happy Returns of the day !!Although the year is different, today is the day of birthday, so you will see a birthday blessing in the output. You can adjust the time of the system and run the program to see if it can remind you when the next birthday is. You can also try to write a Junit unit to test the code to run correctly with your next birthday.
This is very similar to the current date in the first example. This time we use a class called LocalTime. It is a time without date and is close to LocalDate. Here you can also use a static factory method now () to get the current time. The default format is HH: MM: SS: Nnn, and the nnn here is nanoseconds. It can be compared with how to get the current time with Java 8.
LOCALTIME TIME = LOCALTIME.NOW (); System.out.println ("Local Time Now:" + Time); Output Local Time Now: 16: 33: 33.369 // ds, Nano SecondsIt can be seen that the current time does not include the date, because LocalTime has only time and no date.
Many times we need to increase the future time in every minute or second. Java 8 not only provides unchanged 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, don't forget to store this new reference.
LOCALTIME TIME = LOCALTIME.NOW (); LocalTime Newtime = Time.plushours (2); // Adding Two HourS System.Println ("Time after 2 Hours:" + NEWT Ime); Output: Time after 2 Hours: 18: 33: 33.369You can see that after 2 hours of the current time, it is 16: 33: 33.369. Now you can compare it to an old way to add or reduce the old way in Java. At first glance, you know which way is better.
This is similar to the previous example of the previous two hours. Here we will learn how to get the date after 1 week. LocalDate is used to indicate the date without time. It has a Plus () method that can be used to increase the day, week, or month, and Chronounit is used to indicate the unit of time. Because the localdate is also immutable, any modification operation will return a new example, so don't forget to save it.
LOCALDATE NEXTWEEK = TODAY.Plus (1, Chronounit.weeks); System.out.println ("TODAY is:" + TODAY); System.out.println ("Date after 1 Week:" + Next Week); Output: TODAY is : 2014-01-14 Date after 1 Week: 2014-01-21You can see what is the date after 7 days. You can use this method to increase one month, one year, one hour, one minute, or even ten years, check the Chronounit class in the Java API to get more options.
This is the sequel to the previous example. In the above example, we learned how to use the Plus () method of LocalDate to increase the date of date, week or month. Now let's learn how to use the minus () method to find the day of the year.
LocalDate Previousyear = TODAY.MINUS (1, Chronousit.years); System.out.println ("Date BeFore 1 YEAR:" + Previousyear); s (1, year); System.out.println (" Date after 1 year: " + nextyear); Output: date Before 1 year: 2013-01-14 Date after 1 year: 2015-01-14It can be seen that there are two years in total, one is 2013, and the other is 2015, which is the year before and after 2014.
Java 8 comes with a CLOCK class, you can use it to get the current instantaneous time, date or time in a certain time zone. You can use clock to replace System.Currenttimeinmillis () and timezone.getdefault () method.
// Returns the Current Time Based on your System CLOCK and SET To UTC. CLOCK CLOCK = CLOCK.SYSTEMUTC (); System.out.println ("Clock:" + CLOCK); Return Time Based on System CLOCK ZONE CLOCK DefaultClock = Clock.SystemDefaultzone (); System.out.println ("CLOCK:" + Clock); Output: CLOCK: SystemClock [Z] CLOCK: SystemClock [Z]You can use the specified date to compare with this clock, for example, as follows:
Public class myclass {Private CLOCK CLOCK; // Dependency Inject ... Public Void Process (LocalDate EventDate) {if (EVENTDATE.ISBEFORE (LOCALDATE.NOW (C lock)) {...}}}If you need to deal with the dates of different time zones, this is quite convenient.
This is also a common task in actual projects. How do you judge whether a certain date is in front of or behind another date, or just equal? In the Java 8, the LocalDate class has an ISBEFORE () and IsaFTER () methods that can be used to compare two dates. If the date of the call method is earlier than the given date, the ISBEFORE () method will return True.
LOCALDATE TOMOMORROW = LOCALDATE.OF (2014, 1, 15); If (Tommorow.isaFTER (TODAY)) {System.out.println ("Tomorrow Comes after Today");} LocalDate Yesday = TODAY.minus (1, Days ); YesterDay.isBeFore (today) {System.out.println ("Yesterday is Day Before Today"); oadayIt can be seen that the date in Java 8 is relatively simple. No need to use another class like Calendar to complete similar tasks.
Java 8 not only separates the date and time, but also sometimes regions. There are already several groups related to time zones. For example, Zonid represents a certain time zone, and ZonedDateTime represents time with the time zone. It is equivalent to the GregorianCalendar class before the Java 8. Using this class, you can convert the local time into the corresponding time in another time zone, such as the following example:
// date and time with timezone in java 8 zoneid America = zoneid.of ("American/News"); OneDateTime Dateandtimeinnewyork = ZoneDateTime.of (LOCALTDATEANDTIME, American); System.out.println ("Curren Date and Time in a PARTICular Timezone:" + Dateandtimeinnewyork); Output: Current Date and Time in A PARTICular Timezone: 2014-01-14T16: 33.373-05: 00 [American/New_york]It can be compared with the time to convert the local time into GMT time. By the way, as before the Java 8, the text in the corresponding time zone should not be mistaken, otherwise you will encounter such an exception:
Exception in Thread "Main" Java.Time.zone.zonerSeException: UNKNOWN TIME-ZONE ID: Asia/TOKYO AT lesprovider.java:272) at java.time.zone.zonerulesprovider.getrules (Zonerulesprovider.java:227) at java.time.zoneregy.ofid (zoneregy.java:120) at java.time.zoneid.of (zoneid.java:403) at java.time.zoneid.o f (zoneid.java: 351)
Just as MonthDay expresses a duplicate day, Yearmonth is another combination. It represents a date such as credit card repayment date, regular deposit maturity date, and Options expiration date. You can use this class to find out how many days that month, lengthofmonth () This method returns how many days this yearmonth instance is, which is very useful for checking whether it was 28 days in February or 29 days.
Yearmonth CurrenTyearmonth = Yearmonth.now (); System.out.printf ("Day in Month Year %s: %D %N", CurrenTyearmonth.LengThofmonth ();); Yearmonth CreditCardexpiry = Yearmonth.of (2018, month.february );; "Your Credit Card Expires on %S %N", CreditCardexpiry); Output: Day in Month year 2014-01: 31 Your Credit Expires on 2018-02This is not complicated. The LocalDate class has a method of Isleapyear () that can return whether the year corresponding to the current localdate is a leap year. If you still want to repeat the wheel, you can see this code. This is the logic of judging whether a certain year is judged by Java.
if (TODAY.ISLEAPYEAR ()) {System.out.println ("this year is leap year"); A Leap yearYou can check for a few years to see if the results are correct. It is best to write a unit test to test the normal years and leap years.
Another common task is to calculate how many days, how many weeks or years are included between the two given dates. You can use the Java.Time. Period class to complete this function. In the following example, we will calculate a total of several months before the current date and the future date.
LOCALDATE JAVA8Release = LocalDate.of (2014, MONTH.MARCH, 14); Period PeriodtonextJavareser = Period.between (today, java8Release); System.out.println ("Months Left BetWeen Today and Java 8 Release:" + PeriodtonextJavareserase.getmonths ( )); Output: Months Left Between Today and Java 8 Release: 2It can be seen that this month is January, and the release date of the Java 8 is March, so it is 2 months apart.
In Java 8, you can use the ZoneOffset class to represent a certain time zone. For example, India is GMT or UTC5: 30. You can use its static method Zoneoffset.of () method to obtain the corresponding time zone. As long as you get this offset, you can use LocalDateTime and this offset to create an OfficetateTime.
LOCALDALETIME DOTETIME = LOCALDATETIME.OF (2014, Month.january, 14, 19, 30); zoneoffset office = zoneoffset.of ("+05:30"); OfficeTdateTime Date = ffsetdateTime.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: 30It can be seen that the current date is associated with the time zone. Another point is that OfficetDateTime is mainly understood by the machine. If it is for people, you can use the ZoneDateTime class.
If you still remember how to get the current time stamp before Java 8, then this is simply a small dish. The Instant class has a static factory method now () to return the current timestamp, as follows:
Instant Timestamp = Instant.now (); System.out.println ("What Is Value of This Instant" + Timestamp); Output: What is value of this Instant 2014-01-14: 33: 33: 33: .379zIt can be seen that the current timestamp includes the date and time, which is similar to Java.util.date. In fact, Instant is the DATE in front Conversion between measuring, such as date.from (Instant) is used to convert Instant into java.util.date, and date.toinstant () converts the date to Instant.
Before the Java 8, the formatting of the time date is a technical work. Our good partner SimpleDateFormat is not thread -safe, and it seems a bit bulky if it is used as a local variable to format it. Thanks to the local variables of the thread, it has made it useful in a multi -threaded environment, but it has been a long time for Java to maintain this state. This time it introduced a new thread security date and time format. It also comes with some predetermined format, which contains the commonly used date format. For example, in this example, we use the predefined Basic Iso Date format, which will formatted February 14, 2014 to 20140114.
String DayaFtertommorrow = "20140116"; LocalDate Formatted = LocalDate.parse (DayaFertommorrow, DateTimeFormatter.Basic_ISO_DATE); Date geenerator from string %s is %s %n ", dayaFTERTOMMOROW, Formatted); Output: date Generated From String 20140116 IS 2014-01-16
You can see that the date of generation is matched with the value of the specified string, which is slightly different in the date format.
In the above example, we used the built -in time and date format to resolve the date string. Of course, the predetermined format is really good, but sometimes you may still need to use a custom date format. At this time, you have to create a customized date format instance. The date format in this example is "MMM DD YYYY". You can pass the OFPATTERN static method () to the DateTimeFormatter's OFPattern static method (), and it will return an instance. The literal amount of this mode is the same as in the preceding example. For example, M still represents the month, and M is still divided. The invalid mode will throw DateTimeParseException anomalies, but if it is logical errors, for example, it should be used as M when m, so there is no way.
String goodfriday = "APR 18 2014"; Try {DateTimeFormatter Formatter = DateTimeFormatter.ofPattern ("MMM DD YYYY"); local ODFRIDAY, Formatter); System.out.printf ("SuccessFully Parsed String %s, date is%s%n ", goodfriday, Holiday);} Catch (DateTimeParsexception EX) {system.out.printf ("%s is not parsable!%n ", goodfriday); Ex.printstacktr ace ();} output: Successfully Parsed String APR 18 2014, Date is 2014-04-18It can be seen that the value of the date is indeed consistent with the passing string, but the format is different.
In the previous two examples, although we used the DateTimeFormatter class, we mainly parsed the date string. In this example, what we have to do is exactly the opposite. Here we have an instance of the LocalDateTime class, and we want to convert it into a formatted date string. This is the simplest and most convenient way to convert the date into a string in Java so far. The following example will return a formatted string. Like the previous example, we still need to use the specified mode string to create an instance of the DateTimeFormatter class, but the PARSE method of the LocalDate class is not, but its format () method. This method will return a string representing the current date, and the corresponding mode is the defined in the DateTimeFormatter instance that is introduced.
LOCALDALETIME ArrivalDate = LocalDateTime.now (); Try {DateTimeFormatter Format = DatetimeFormatter.ofpatter rrivalDate.Format (format); System.out.printf ("Arriving at: % s%n ", landing);} Catch (dateTimeexception ex) {system.out.printf ("%s can'T formatted!%n ", arrivalDate); ex.printstacktrace ();} output: Arriv ing at: jan 14 2014 04:33 PMIt can be seen that the current time is represented by the given "MMM DD YYYY HH: MM A" mode. It contains the month of the three letters and the time expressed by AM and PM.
After reading these examples, I believe you have a certain understanding of the new set of time and date of Java 8. Now we look back at some of the key elements of this new API.
Each Java developer should at least understand these five categories of these new APIs:
The main bag of this library is Java.Time, which contains the class, time, instantaneous and duration of representative date, time, instantaneous and duration. It has two sub -Package, one is java.time.Foramt. What is this use is obvious, and the other is Java.Time.tempages, which can access each field from a lower level.
The time zone refers to areas that share the same standard time on the planet. There is a unique identifier in each time zone, as well as the format of a region/city (ASIA/Tokyo) and a offset time starting from Greenwich time. For example, the offset time of Tokyo is +09: 00.
The OfficeDateTime class actually contains LocalDateTime and Zoneoffset. It is used to indicate a complete date (+06: 00 or -08: 00) that contains Greenwita's time offset (+/-hour: points, such as +06: 00 or -08: 00). Essence
DateTimeFormatter class is used for formatting and analysis of the date in Java. Unlike SimpleDateFormat, it is unchanged and thorough safe. If necessary, it can be assigned to a static variable. The DateTimeFormatter class provides many pre -defined formats, and you can also customize the format you want. Of course, according to the agreement, it also has a PARSE () method to convert the string into a date. If any error occurs during the conversion period, it will throw out DateTimeParsexception abnormalities. Similarly, the DateFormatter class also has a format () method for the formatting date. It will throw DateTimeException anomaly if it is wrong.
Let's say, the two date formats of "MMM D YYYY" and "MMM DD YYYY" are also slightly different. The former can identify the two string of "Jan 2 2014" and "Jan 14 2014", and if the latter is passed in "Jan 2 2014" will report an error because it expects two characters to pass in the month. In order to solve this problem, in the case of the number of digits, you have to make up 0 in front. For example, "Jan 2 2014" should be changed to "Jan 02 2014".
This is about the new time date of Java 8. These brief examples are enough to understand some of the new APIs in this new API. Since it is explained based on the actual task, when it is encountered in Java, it is not necessary to look for time and date. We have learned how to create and modify the date of time. We also understand the differences between the pure date, the date of time, and the time zone of the time zone. We know how to compare two dates, how to find a certain day to the specified date, such as the next birthday, how many days there are on the anniversary or insurance day. We have also learned how to analyze and format the date in the method of thread security in Java 8 without having to use a thread local variable or a third -party library. The new API is competent for any task related to time date.
If you are also interested in Java 8 tutorials, you can take a look at the following tutorials:
English original link