Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to deal with date and time in Java8

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to deal with date and time in Java8". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to deal with date and time in Java8.

Example 1. Get today's date in Java 8

The LocalDate in Java 8 is used to indicate the date of the day. Unlike java.util.Date, it has only dates and no time. Use this class when you only need to represent the date.

1LocalDate now = LocalDate.now (); 2System.out.println (now)

The result is:

12018-06-20

The above code creates the date of the day without time information. The format of the printed date is very friendly, unlike the old Date class that prints out a pile of unformatted information.

Example 2. Get the information of year, month and day in Java 8

The LocalDate class provides a quick way to get the year, month, and day, and its instance contains many other date properties. By calling these methods, you can easily get the required date information without having to rely on the java.util.Calendar class as before.

1LocalDate now = LocalDate.now (); 2int year = now.getYear (); 3int monthValue = now.getMonthValue (); 4int dayOfMonth = now.getDayOfMonth (); 5System.out.printf ("year =% d, month =% d, day =% d", year, monthValue, dayOfMonth)

The result is:

1year = 2018, month = 6, day = 20 example 3, processing specific dates in Java 8

In the first example, we can easily create the date of the day through the static factory method now (). You can also call another useful factory method, LocalDate.of (), to create any date, which needs to pass in the year, month, and day as parameters to return the corresponding LocalDate instance. The advantage of this method is that it does not make the design mistakes of the old API, such as the year starts in 1900, the month starts at 0, and so on. Date WYSIWYG, as shown in the following example, shows June 20, without any hidden organs.

1LocalDate date = LocalDate.of (2018, 06, 20); 2System.out.println (date)

You can see that the creation date is exactly as expected, exactly as it was written on June 20, 2018.

Example 4. Determine whether two dates are equal in Java 8

In real life, one kind of time processing is to judge whether two dates are equal. You often check to see if today is a special day, such as a birthday, anniversary or non-trading day. At this point, it is necessary to compare the specified date with a specific date, such as determining whether the day is a holiday. The following example will help you solve the problem in Java 8. You must have thought of it. LocalDate overloads the equal method. Take a look at the following example:

1LocalDate now = LocalDate.now (); 2LocalDate date = LocalDate.of (2018, 06, 20); 3if (date.equals (now)) {4 System.out.println ("same day"); 5}

The two dates we compared in this example are the same. Note that if the compared date is character-based, it needs to be parsed into a date object before making a judgment.

Example 5. Check for periodic events such as birthdays in Java 8

Another date-time process in Java is to check periodic events such as monthly bills, wedding anniversaries, EMI days, or insurance payment dates. If you work on an e-commerce site, there must be a module to send greeting emails to customers during holidays such as Christmas and Thanksgiving. How do you check these festivals or other periodic events in Java? The answer is the MonthDay class. This category combines months and days, excluding years, which means you can use it to judge that events occur every year. Similar to this class is a YearMonth class. These classes are also immutable and thread-safe value types. Let's check for periodic events through MonthDay:

1LocalDate now = LocalDate.now (); 2LocalDate dateOfBirth = LocalDate.of (2018, 06, 20); 3MonthDay birthday = MonthDay.of (dateOfBirth.getMonth (), dateOfBirth.getDayOfMonth ()); 4MonthDay currentMonthDay = MonthDay.from (now); 5if (currentMonthDay.equals (birthday)) {6 System.out.println ("Happy Birthday"); 7} else {8 System.out.println ("Sorry, today is not your birthday"); 9}

Result: (note: getting the current time may not be the same as when you look at it, so this result may not be the same as when you are looking at it.)

1Happy Birthday

As long as the date of the day matches the birthday, congratulations will be printed in any year. You can integrate the program into the system clock to see if you will be reminded on your birthday, or write a unit test to check that the code is running correctly.

Example 6. Get the current time in Java 8

Much like the Java 8 example of getting a date, it uses the LocalTime class, a close relative of LocalDate that has only time but no date. You can call the static factory method now () to get the current time. The default format is hh:mm:ss:nnn.

1LocalTime localTime = LocalTime.now (); 2System.out.println (localTime)

Results:

113:35:56.155

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

Example 7. How to add hours to the existing time

It is common to calculate future time by adding hours, minutes, and seconds. In addition to the benefits of immutable types and thread safety, Java 8 provides a better plusHours () method to replace add () and is compatible. Note that these methods return a completely new instance of LocalTime, which must be assigned with a variable because of its immutability.

1LocalTime localTime = LocalTime.now (); 2System.out.println (localTime); 3LocalTime localTime1 = localTime.plusHours (2); / / add 2 hours 4System.out.println (localTime1)

Results:

113:41:20.721215:41:20.721

As you can see, the new time is an increase of 2 hours over the current time of 13, 14, 41, 20. 721.

Example 8. How to calculate the date a week later

Similar to the previous example, which calculates the time two hours later, this example calculates the date one week later. LocalDate dates do not contain time information, and its plus () method is used to add days, weeks, and months, which are declared by the ChronoUnit class. Since LocalDate is also an immutable type, you must assign a value with a variable when it is returned.

1LocalDate now = LocalDate.now (); 2LocalDate plusDate = now.plus (1, ChronoUnit.WEEKS); 3System.out.println (now); 4System.out.println (plusDate)

Results:

12018-06-2022018-06-27

You can see that the new date is seven days from the same day, that is, one week. You can add a month, a year, an hour, a minute or even a century in the same way. For more options, check out the ChronoUnit class in Java 8 API.

Example 9. Calculate the date before or after one year

Continuing the above example, we used LocalDate's plus () method to increase the number of days, weeks, or months. In this example, we use the minus () method to calculate the date of one year ago.

1LocalDate now = LocalDate.now (); 2LocalDate minusDate = now.minus (1, ChronoUnit.YEARS); 3LocalDate plusDate1 = now.plus (1, ChronoUnit.YEARS); 4System.out.println (minusDate); 5System.out.println (plusDate1)

Results:

12017-06-2022019-06-20 example 10, Clock clock class using Java 8

Java 8 adds a Clock clock class to get the current timestamp, or date-time information under the current time zone. Places where System.currentTimeInMillis () and TimeZone.getDefault () were previously used can be replaced with Clock.

1Clock clock = Clock.systemUTC (); 2Clock clock1 = Clock.systemDefaultZone (); 3System.out.println (clock); 4System.out.println (clock1)

Results:

1SystemClock2SystemClockAn example 11. How to use Java to determine whether a date is earlier or later than another date

Another common operation at work is how to determine whether a given date is greater or less than a certain day. In Java 8, the LocalDate class has two methods, isBefore () and isAfter (), for comparing dates. When the isBefore () method is called, it returns true if the given date is less than the current date.

1 LocalDate tomorrow = LocalDate.of (2018 tomorrow.isAfter (now)) {3 System.out.println ("Tomorrow comes after today"); 4} 5 LocalDate yesterday = now.minus (1, ChronoUnit.DAYS); 6 if (yesterday.isBefore (now)) {7 System.out.println ("Yesterday is day before today"); 8}

Comparing dates in Java 8 is so convenient that you don't need to use additional Calendar classes to do the basics.

Example 12. Working with time zones in Java 8

Java 8 separates not only the date and time, but also the time zone. There is now a series of separate classes such as ZoneId to deal with a specific time zone, and the ZoneDateTime class to represent time under a particular time zone. Before Java 8, this was done by the GregorianCalendar class.

1ZoneId america = ZoneId.of ("America/New_York"); 2LocalDateTime localtDateAndTime = LocalDateTime.now (); 3ZonedDateTime dateAndTimeInNewYork = ZonedDateTime.of (localtDateAndTime, america); 4System.out.println (dateAndTimeInNewYork); example 13, how to represent a fixed date such as credit card expiration, the answer lies in YearMonth

Similar to the example where MonthDay checks for duplicate events, YearMonth is another composite class that represents the credit card expiration date, FD expiration date, futures option expiration date, and so on. You can also use this class to get the total number of days of the month, and the lengthOfMonth () method of the YearMonth instance can return the number of days of the month, which is very useful when judging whether there are 28 or 29 days in February.

1YearMonth currentYearMonth = YearMonth.now (); 2System.out.printf ("Days in month year% s:% d% n", currentYearMonth, currentYearMonth.lengthOfMonth ()); 3YearMonth creditCardExpiry = YearMonth.of (2018, Month.FEBRUARY); 4System.out.printf ("Your credit card expires on% s% n", creditCardExpiry)

Results:

1Days in month year 2018-06: 302Your credit card expires on 2018-02 example 14. How to check for leap years in Java 8

The LocalDate class has a useful method, isLeapYear (), to determine whether the instance is a leap year.

Example 15. Calculate the number of days and months between two dates

A 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 calculations. In the following example, we calculate the number of months between that day and a future day.

1LocalDate date = LocalDate.of (2019, Month.MARCH, 20); 2Period period = Period.between (now, date); 3System.out.println ("still in the next time" + period.getMonths () + "month"); example 16, date and time containing jet lag information

In Java 8, the ZoneOffset class is used to represent the time zone. For example, the difference between India and the GMT or UTC standard time zone is + 05:30, and the corresponding time zone can be obtained through the ZoneOffset.of () static method. Once you have the jet lag, you can create an OffSetDateTime object by passing in LocalDateTime and ZoneOffset.

1LocalDateTime datetime = LocalDateTime.of (2014, Month.JANUARY, 14je 19jol 30); 2ZoneOffset offset = ZoneOffset.of ("+ 05:30"); 3OffsetDateTime date = OffsetDateTime.of (datetime, offset); 4System.out.println ("Date and Time with timezone offset in Java:" + date); example 17, get the current timestamp in Java 8

If you remember how Java 8 used to get the current timestamp, you're finally off the hook. The Instant class has a static factory method now () that returns the current timestamp, as shown below:

1Instant timestamp = Instant.now (); 2System.out.println (timestamp)

Results:

12018-06-20T06:35:24.881Z

Both date and time are included in the timestamp information, much like java.util.Date. In fact, the Instant class is indeed equivalent to the Date class before Java 8, you can use the respective conversion methods of the Date class and the Instant class to convert each other, for example: Date.from (Instant) to convert Instant to java.util.Date,Date.toInstant () is to convert the Date class to the Instant class.

Example 18. How to use predefined formatting tools to parse or format dates in Java 8

In the pre-Java 8 world, date and time formatting was weird, and the only helper class, SimpleDateFormat, was non-thread-safe and cumbersome to use as local variable parsing and formatting dates. Fortunately, thread local variables can make it available in a multithreaded environment, but this is a thing of the past. Java 8 introduces a new date-time formatting tool that is thread-safe and easy to use. It comes with some commonly used built-in formatting tools.

Example 19. How to parse a date in Java using a custom formatting tool

Although the built-in formatting tool is easy to use, it is sometimes necessary to define a specific date format. You can call the ofPattern () static method of DateTimeFormatter and pass in any format to return its instance, with the same characters as before, M for month and m for minutes. A DateTimeParseException exception will be thrown if the format is not standardized, but it will not be thrown if it is just a logic error that writes M as m.

Example 20. How to convert a date to a string in Java 8

The last two are mainly parsing dates from strings. Now let's turn around and convert the LocalDateTime date instance to a string in a specific format. This is by far the easiest way to convert Java dates to strings. The following example returns a formatted string that represents the date. As before, you still need to create an DateTimeFormatter instance and pass in the format, but this time you call the format () method instead of the parse () method. This method converts the incoming date to a string in the specified format.

1LocalDateTime arrivalDate = LocalDateTime.now (); 2try {3 DateTimeFormatter format = DateTimeFormatter.ofPattern ("MMMdd yyyy hh:mm a"); 4 String landing = arrivalDate.format (format); 5 System.out.printf ("Arriving at:% s% n", landing); 6} catch (DateTimeException ex) {7 System.out.printf ("% s can't be formatted% n", arrivalDate); 8 ex.printStackTrace (); 9} Java 8 focus of date time API

Through these examples, you must have mastered the new knowledge points of Java 8 date and time API. Now let's review the main points of using this elegant API:

1) javax.time.ZoneId acquisition time zone is provided.

2) LocalDate and LocalTime classes are provided.

3) all date and time API of Java 8 are immutable and thread-safe, while java.util.Date and SimpleDateFormat in existing Date and Calendar API are non-thread-safe.

4) the main package is java.time, which contains classes that represent dates, times, and intervals. There are two subpackages, java.time.format, for formatting and java.time.temporal for lower-level operations.

5) the time zone represents the standard time commonly used in a region of the earth. Each time zone has a code name, which is usually made up of regions / cities (Asia/Tokyo), plus a time difference from Greenwich or UTC. For example, the time difference in Tokyo is + 09:00.

6) the OffsetDateTime class actually combines the LocalDateTime class and the ZoneOffset class. Used to represent complete date (year, month, day) and time (hours, minutes, seconds, nanoseconds) information containing the time difference from Greenwich or UTC.

7) the DateTimeFormatter class is used for formatting and parsing time. Unlike SimpleDateFormat, this class is immutable and thread-safe, and static constants can be assigned values when needed. The DateTimeFormatter class provides a large number of built-in formatting tools, but also allows you to customize. In terms of conversion, parse () is also provided to parse the string into a date, and a DateTimeParseException will be thrown if there is a parsing error. The DateTimeFormatter class also has format () to format the date, throwing a DateTimeException exception if something goes wrong.

8) add that there are some subtle differences between the date format "MMM d yyyy" and "MMM dd yyyy". The first format can parse "Jan 2 2014" and "Jan 14 2014", while the second format will throw an exception when parsing "Jan 2 2014", because the second format requires that the day must be two digits. If you want to correct it, you must fill in the preceding zero when the date has only single digits, which means that "Jan 2 2014" should be written as "Jan 02 2014".

Thank you for your reading, the above is the content of "how to deal with date and time in Java8". After the study of this article, I believe you have a deeper understanding of how to deal with date and time in Java8. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report