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

What are the practices of 18 Java8 date processing

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article will explain in detail the practice of dealing with 18 Java8 dates, and the content of the article is of high quality, so the editor will share it with you for reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

Java 8 introduces a new date-time API, and in the tutorials we will learn how to use the new API through some simple examples.

The way Java handles dates, calendars, and times has been criticized by the community, setting java.util.Date to a variable type, and the non-thread safety of SimpleDateFormat makes its application very limited.

The new API is based on the ISO standard calendar system, and all classes under the java.time package are immutable and thread-safe.

Get today's date in sample 1: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.

Package com.shxt.demo02; import java.time.LocalDate; public class Demo01 {public static void main (String [] args) {LocalDate today = LocalDate.now (); System.out.println ("date today:" + today);}}

Get the information of year, month and day in example 2:Java 8

Package com.shxt.demo02; import java.time.LocalDate; public class Demo02 {public static void main (String [] args) {LocalDate today = LocalDate.now (); int year = today.getYear (); int month = today.getMonthValue (); int day = today.getDayOfMonth (); System.out.println ("year:" + year); System.out.println ("month:" + month); System.out.println ("day:" + day);}}

A specific date is handled in example 3:Java 8

We can easily create the date of the day through the static factory method now (), and 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 approach is that it doesn't make the same design mistakes as the old APIs, such as the year begins in 1900, the month starts at 0, and so on.

Package com.shxt.demo02; import java.time.LocalDate; public class Demo03 {public static void main (String [] args) {LocalDate date = LocalDate.of; System.out.println ("Custom date:" + date);}}

Determine whether two dates are equal in example 4:Java 8

Package com.shxt.demo02; import java.time.LocalDate; public class Demo04 {public static void main (String [] args) {LocalDate date1 = LocalDate.now (); LocalDate date2 = LocalDate.of (2018 date1.equals (date2)) {System.out.println ("time is equal");} else {System.out.println ("time is not equal");}

Check for periodic events such as birthdays in example 5:Java 8

Package com.shxt.demo02; import java.time.LocalDate; import java.time.MonthDay; public class Demo05 {public static void main (String [] args) {LocalDate date1 = LocalDate.now (); LocalDate date2 = LocalDate.of (2018 date2.getDayOfMonth 2); MonthDay birthday = MonthDay.of (date2.getMonth (), date2.getDayOfMonth ()); MonthDay currentMonthDay = MonthDay.from (date1); if (currentMonthDay.equals (birthday)) {System.out.println ("your birthday") } else {System.out.println ("your birthday is not here yet");}

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.

Get the current time in sample 6:Java 8

Package com.shxt.demo02; import java.time.LocalTime; public class Demo06 {public static void main (String [] args) {LocalTime time = LocalTime.now (); System.out.println ("get the current time without date:" + time);}}

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

Get the current time in sample 7:Java 8

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.

Package com.shxt.demo02; import java.time.LocalTime; public class Demo07 {public static void main (String [] args) {LocalTime time = LocalTime.now (); LocalTime newTime = time.plusHours (3); System.out.println ("time after three hours:" + newTime);}}

Example 8:Java 8 how to calculate the date one week later

Similar to the previous example, which calculates the time after three hours, 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.

Package com.shxt.demo02; import java.time.LocalDate; import java.time.temporal.ChronoUnit; public class Demo08 {public static void main (String [] args) {LocalDate today = LocalDate.now (); System.out.println ("Today's date is:" + today); LocalDate nextWeek = today.plus (1, ChronoUnit.WEEKS); System.out.println ("date in a week:" + nextWeek);}}

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:Java 8 calculates the date before or after one year

Using minus () method to calculate the date of one year ago

Package com.shxt.demo02; import java.time.LocalDate; import java.time.temporal.ChronoUnit; public class Demo09 {public static void main (String [] args) {LocalDate today = LocalDate.now (); LocalDate previousYear = today.minus (1, ChronoUnit.YEARS); System.out.println ("date of one year ago:" + previousYear); LocalDate nextYear = today.plus (1, ChronoUnit.YEARS); System.out.println ("date after one year:" + nextYear);}}

Clock clock class for example 10: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.

Package com.shxt.demo02; import java.time.Clock; public class Demo10 {public static void main (String [] args) {/ / Returns the current time based on your system clock and set to UTC. Clock clock = Clock.systemUTC (); System.out.println ("Clock:" + clock.millis ()); / / Returns time based on system clock zone Clock defaultClock = Clock.systemDefaultZone (); System.out.println ("Clock:" + defaultClock.millis ());}}

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 types of methods, isBefore () and isAfter (), to compare dates. When the isBefore () method is called, it returns true if the given date is less than the current date.

Package com.shxt.demo02; import java.time.LocalDate; import java.time.temporal.ChronoUnit; public class Demo11 {public static void main (String [] args) {LocalDate today = LocalDate.now (); LocalDate tomorrow = LocalDate.of (2018 tomorrow.isAfter (today)) {System.out.println ("after date:" + tomorrow);} LocalDate yesterday = today.minus (1, ChronoUnit.DAYS); if (yesterday.isBefore (today)) {System.out.println ("previous date:" + yesterday) }

Processing time zone in example 12: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. The following example shows how to convert time in this time zone to time in another time zone.

Package com.shxt.demo02; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; public class Demo12 {public static void main (String [] args) {/ / 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);}}

Example 13: how to represent a fixed date such as the expiration of a credit card, 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 number of days in the month, and the lengthOfMonth () method of the YearMonth instance returns the number of days in the month, which is useful when determining whether there are 28 or 29 days in February.

Package com.shxt.demo02; import java.time.*; public class Demo13 {public static void main (String [] args) {YearMonth currentYearMonth = YearMonth.now (); System.out.printf ("Days in month year% s:% d% n", currentYearMonth, currentYearMonth.lengthOfMonth ()); YearMonth creditCardExpiry = YearMonth.of (2019, Month.FEBRUARY); System.out.printf ("Your credit card expires on% s% n", creditCardExpiry);}}

Example 14: how to check for leap years in Java 8

Package com.shxt.demo02; import java.time.LocalDate; public class Demo14 {public static void main (String [] args) {LocalDate today = LocalDate.now (); if (today.isLeapYear ()) {System.out.println ("This year isLeap year");} else {System.out.println ("2018 is not 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.

Package com.shxt.demo02; import java.time.LocalDate; import java.time.Period; public class Demo15 {public static void main (String [] args) {LocalDate today = LocalDate.now (); LocalDate java8Release = LocalDate.of (2018, 12, 14); Period periodToNextJavaRelease = Period.between (today, java8Release); System.out.println ("Months left between today and Java 8 release:" + periodToNextJavaRelease.getMonths ());}}

Example 16: get the current timestamp in Java 8

The Instant class has a static factory method now () that returns the current timestamp, as shown below:

Package com.shxt.demo02; import java.time.Instant; public class Demo16 {public static void main (String [] args) {Instant timestamp = Instant.now (); System.out.println ("What is value of this instant" + timestamp.toEpochMilli ());}}

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.

How to use predefined formatting tools to parse or format dates in sample 17:Java 8

Package com.shxt.demo02; import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class Demo17 {public static void main (String [] args) {String dayAfterTommorrow = "20180205"; LocalDate formatted = LocalDate.parse (dayAfterTommorrow, DateTimeFormatter.BASIC_ISO_DATE); System.out.println (dayAfterTommorrow+ "formatted date is:" + formatted);}}

Example 18: string interchange date type

Package com.shxt.demo02; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class Demo18 {public static void main (String [] args) {LocalDateTime date = LocalDateTime.now (); DateTimeFormatter format1 = DateTimeFormatter.ofPattern ("yyyy/MM/dd HH:mm:ss"); / / date transfer string String str = date.format (format1); System.out.println ("date to string:" + str) DateTimeFormatter format2 = DateTimeFormatter.ofPattern ("yyyy/MM/dd HH:mm:ss"); / / string date LocalDate date2 = LocalDate.parse (str,format2); System.out.println ("date type:" + date2);}}

This is the end of the practice of dealing with 18 Java8 dates. I hope the above content can be helpful to you and learn more knowledge. If you think the article is good, you can share it for more people to see.

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

Development

Wechat

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

12
Report