18 Java8 date handling practices, too useful for programmers!

Example 1: Get today’s date in Java 8 LocalDate in Java 8 is used to indicate the current date. Unlike java.util.Date, it contains only dates and no time. Use this class when you only need to represent dates. package com.shxt.demo02;

import java.time.LocalDate;

public class Demo01 { public static void main(String[] args) { LocalDate today = LocalDate.now(); System.out.println(” today’s date :”+today); }} 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);

We created the date of the day very easily with the static factory method now(). You can also create any date by calling another useful factory method, localdate.of (), which takes the year, month, and day as arguments. Returns the corresponding LocalDate instance. The advantage of this approach is that you don’t make the old API design mistakes, such as the year starting at 1900, the month starting at 0, etc. package com.shxt.demo02;

import java.time.LocalDate;

Public class Demo03 {public static void main(String[] args) {LocalDate date = localdate.of (2018,2,6); System.out.println(” custom date :”+date); }} Example 4: Check whether two dates are equal in 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,2,5 (2018);

If (date1.equals(date2)){system.out.println (” time equals “); }else{system.out.println (” time is different “); }

}} Example 5: Check for periodic events like birthdays in 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,2,6 (2018); MonthDay birthday = MonthDay.of(date2.getMonth(),date2.getDayOfMonth()); MonthDay currentMonthDay = MonthDay.from(date1);

If (currentMonthday.equals (birthday)){system.out.println (” is your birthday “); }else{system.out.println (” Your birthday hasn’t come yet “); }

}} As long as the date of the day matches the birthday, no matter which year it is, a congratulatory message will be printed. You can integrate your program into the system clock to see if you get a birthday reminder, or write a unit test to see if your code works correctly. Example 6: Get the current time in 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 current time, no date :”+time);

}} You can see that the current time contains only the time information, no date. Example 7:Java 8 to obtain the current time by adding hours, minutes, seconds to calculate the future time is common. In addition to the benefits of type-invariant and thread-safety, Java 8 provides a better plusHours() method to replace Add () and is compatible. Note that these methods return a brand new LocalTime instance, which must be assigned by 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 3 hours :”+newTime);

}} Example 8: How Java 8 computes the date after one week is similar to the previous example, which computes the date after three hours. LocalDate does not contain time information; its plus() method adds days, weeks, and months, which are declared by the ChronoUnit class. Since LocalDate is also an immutable type, it must be returned with a variable assignment. 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(” nextWeek :”+nextWeek);

}} You can see that the new date is 7 days from the current date, that is, a week. You can add a month, a year, an hour, a minute or even a century in the same way, For more options, see the ChronoUnit class in the Java 8 API example 9:Java 8 calculates dates a year ago or later using the minus() method to calculate dates a 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(” year ago date: “+ previousYear);

LocalDate nextYear = today.plus(1, ChronoUnit.YEARS); System.out.println(” nextYear :”+nextYear);

Java 8 adds a Clock Clock class to get the current timestamp, or date-time information in the current time zone. Previously used System. CurrentTimeInMillis () and TimeZone. GetDefault () places available Clock is replaced. 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());

Another common operation in work is how to determine whether a given date is greater than or less than a certain day. In Java 8, the LocalDate class has two classes of methods, isBefore() and isAfter(), to compare dates. The isBefore() method is called and 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,2,6 (2018); If (tomorrow. IsAfter (today)){system.out.println (” after date :”+tomorrow); }

LocalDate yesterday = today.minus(1, ChronoUnit.DAYS); If (yesterday. IsBefore (today)){system.out.println (” yesterday :”+yesterday); Java 8 not only separates date and time, but also time zones. There is now a separate set of classes such as ZoneId to handle a particular time zone, and ZoneDateTime to represent the time in a particular time zone. This was done by the GregorianCalendar class until Java 8. The following example shows how to convert time in one 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 fixed dates such as credit card expiration. The answer is similar to the example of checking duplicate events with YearMonth and MonthDay. YearMonth is another combination class used to represent credit card expiration, FD expiration, futures option expiration, etc. You can also use this class to get the total number of days in the month. The YearMonth instance’s lengthOfMonth() method returns the number of days in the month, useful in determining whether February has 28 or 29 days. 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 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 is Leap year”);         }else {             System.out.println(“2018 is not a Leap year”);         }

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 this example, we count the number of months between today and some 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() );

The Instant class has a static factory method now() that returns the current timestamp, as follows: 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()); }} Timestamp information contains both the Date and time, much like java.util.Date. In fact, the Instant class is exactly the same as the Date class before Java 8. You can convert the Date class and Instant class to each other using their respective conversion methods, for example: Date.from(Instant) converts Instant to java.util.date, and date.toinstant () converts the Date class toInstant. Example 17: How to parse or format the date package com.shxt.demo02 using predefined formatting tools in Java 8;

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); Println (dayAfterTommorrow+” Formatted date: “+formatted); }} Example 18: String transfer 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”); String STR = date.format(format1);

System.out.println(” date converted to string :”+ STR);

DateTimeFormatter format2 = DateTimeFormatter.ofPattern(“yyyy/MM/dd HH:mm:ss”); Parse (STR,format2); // String datedate2 = localdate.parse (STR,format2); System.out.println(” date type :”+date2);

}}

Focus on Java architect technology sharing, free send me a full set of Java architect promotion materials (Java architect exchange enterprise Q/: 445820908).