Java 8 date handling
Java 8 has introduced a new date and time API, and in this tutorial we’ll walk through some simple examples to learn how to use the new API.
Java has long been criticized by the community for its handling of dates, calendars, and times. The mutable type of Java.util. Date and the non-thread-safe nature of SimpleDateFormat have limited its use.
The new API is based on the ISO standard calendar system, and all classes in the java.time package are immutable and thread-safe.
Example 1: Get today’s date in Java 8
LocalDate in Java 8 is used to represent the date of the day. 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); }} /* Result :2018-02-05 */Copy the code
Example 2: Get year, month, and day information in 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); }}Copy the code
Example 3: Processing specific dates in Java 8
You can also call another useful factory method, localdate.of (), to create any date. This method takes the year, month, and day as arguments and 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); }}Copy the code
Example 4: Determine if 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 "); }}}Copy the code
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 "); }}}Copy the code
As long as the date matches the birthday, a congratulatory message is printed regardless of the year. 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); }}Copy the code
You can see that the current time only contains time information, no date
Example 7: Get the current time in Java 8
It is common to calculate future time by adding hours, minutes, and seconds. 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); }}Copy the code
Example 8: How does Java 8 calculate the date one week from now
Similar to the previous example calculating the time after 3 hours, this example calculates the date after 1 week. 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); }}Copy the code
You can see that the new date is 7 days from the date, which 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 computes dates one year ago or one year from now
Use the minus() method to calculate dates 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(" year ago date: "+ previousYear); LocalDate nextYear = today.plus(1, ChronoUnit.YEARS); System.out.println(" nextYear :"+nextYear); }}Copy the code
Example 10: The Java 8 Clock Clock class
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()); }}Copy the code
Example 11: How do I use Java to determine whether a date is earlier or later than another date
Another common operation in work is how do you tell if 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); }}}Copy the code
Example 12: Dealing with time zones in Java 8
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);
}
}
Copy the code
Example 13: How to express a fixed date such as YearMonth when a credit card expires
Similar to the example of MonthDay checking for duplicate events, YearMonth is another combinative class that represents credit card expiration, FD expiration, futures option expiration, and so on. 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); }}Copy the code
Example 14: How do I 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"); }}}Copy the code
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 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() ); }}Copy the code
Example 16: Get the current timestamp in Java 8
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()); }}Copy the code
The 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 dates using predefined formatting tools in 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); Println (dayAfterTommorrow+" Formatted date: "+formatted); }}Copy the code
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); }}Copy the code