Yunqi information:[ Click to see more industry information]
Here you can find the first-hand cloud information of different industries. What are you waiting for? Come on!
brief introduction
Along with lambda expressions, streams and a series of small optimizations, Java 8 introduces a new date time API.
The disadvantage of Java in dealing with date, calendar and time java.util.Date Setting it to a mutable type and the non thread safety of SimpleDateFormat make its application very limited. Then add new features to java8.
One of the many benefits of the new API is that it defines the concept of date and time, such as instant, duration, date, time, time zone and period.
At the same time, it inherits the time processing method of Joda library according to human language and computer. Unlike the old version, the new API is based on the ISO standard calendar system, java.time All classes under the package are immutable and thread safe.
Key categories
Instant: instantaneous instance.
LocalDate: local date, excluding specific time. For example, 2014-01-14 can be used to record birthdays, anniversaries, franchise days, etc.
LocalTime: local time, excluding date.
LocalDateTime: a combination of date and time, but does not contain time difference and time zone information.
Zonedatetime: the most complete datetime, including time zone and time difference relative to UTC or Greenwich.
The new API also introduces ZoneOffSet and ZoneId classes, making it easier to solve the time zone problem. The DateTimeFormatter class that parses and formats time is also redesigned.
actual combat
In the tutorial, we will learn how to use the new API through some simple examples, because only in the actual project, is the fastest way to learn new knowledge and new technology.
- Get current date
Java 8 In LocalDate Used to indicate the date of the day. and java.util.Date Different, it only has date, not time. Use this class when you only need to represent dates //Get today's date public void getCurrentDate(){ LocalDate today = LocalDate.now(); System.out.println("Today's Local date : " + today); //This is for comparison Date date = new Date(); System.out.println(date); }
The above code creates the Date of the day, excluding the time information. The printed Date format is very friendly, unlike the Date class, which prints out a bunch of unformatted information.
- Get the year, month and day information
LocalDate provides a shortcut to get the year, month, and day. In fact, there are many other date attributes in the example. By calling these methods, you can easily get the date information you need, without relying on it as before java.util.Calendar Class.
//Get the year, month and day information public void getDetailDate(){ LocalDate today = LocalDate.now(); int year = today.getYear(); int month = today.getMonthValue(); int day = today.getDayOfMonth(); System.out.printf("Year : %d Month : %d day : %d t %n", year, month, day); }
3. Process specific dates
In the first example, we created the date of the day very easily through the static factory method now(). We can also call another useful factory method LocalDate.of() create any date. The method needs to pass in year, month and day as parameters to return the corresponding localdate instance. The advantage of this method is that it doesn't make old API design mistakes again, for example, the year starts from 1900, the month starts from 0, and so on. What you see is what you get, as the example below shows January 21, which is straightforward.
//Process specific dates public void handleSpecilDate(){ LocalDate dateOfBirth = LocalDate.of(2018, 01, 21); System.out.println("The specil date is : " + dateOfBirth); }
4. Judge whether two dates are equal
In real life, a kind of time processing is to judge whether two dates are equal. There are always problems like this in project development. The following example will help you solve this problem in Java 8. LocalDate overloads the equal method. Note that if the date of comparison is character type, it needs to be resolved into Date object before judgment.
See the following example:
//Judge whether two dates are equal public void compareDate(){ LocalDate today = LocalDate.now(); LocalDate date1 = LocalDate.of(2018, 01, 21); if(date1.equals(today)){ System.out.printf("TODAY %s and DATE1 %s are same date %n", today, date1); } }
5. Check for periodic events like birthdays
Another processing of date and time in Java is to check periodic events such as birthdays, anniversaries, legal holidays (National Day and Spring Festival), or sending emails to customers at a fixed time every month. How do you check these festivals or other periodic events in Java? The answer is the MonthDay class. This class combines the month and the day, eliminating the year, which means you can use it to determine that events happen every year. Similar to this class, there is also a YearMonth class. These classes are also immutable and thread safe value types. Next, we use MonthDay to check for periodic events:
//Processing recurring dates public void cycleDate(){ LocalDate today = LocalDate.now(); LocalDate dateOfBirth = LocalDate.of(2018, 01, 21); MonthDay birthday = MonthDay.of(dateOfBirth.getMonth(), dateOfBirth.getDayOfMonth()); MonthDay currentMonthDay = MonthDay.from(today); if(currentMonthDay.equals(birthday)){ System.out.println("Many Many happy returns of the day !!"); }else{ System.out.println("Sorry, today is not your birthday"); } }
6. Get the current time
Similar to the example of getting date, getting time uses the LocalTime class, a close relative of LocalDate who only has 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.
//Get current time public void getCurrentTime(){ LocalTime time = LocalTime.now(); System.out.println("local time now : " + time); }
7. Add hours to the existing time
Java 8 provides a better way to replace add() with the plusHours() method and is compatible. Note that these methods return a brand-new instance of LocalTime. Because of its non variability, you must use variables to assign values after returning.
//Add hours public void plusHours(){ LocalTime time = LocalTime.now(); LocalTime newTime = time.plusHours(2); // Add two hours System.out.println("Time after 2 hours : " + newTime); }
//How to calculate the date after one week public void nextWeek(){ LocalDate today = LocalDate.now(); LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS); //Use variable assignment System.out.println("Today is : " + today); System.out.println("Date after 1 week : " + nextWeek); }
//Calculate the date before or after one year public void minusDate(){ LocalDate today = LocalDate.now(); LocalDate previousYear = today.minus(1, ChronoUnit.YEARS); System.out.println("Date before 1 year : " + previousYear); LocalDate nextYear = today.plus(1, ChronoUnit.YEARS); System.out.println("Date after 1 year : " + nextYear); }
public void clock(){ // Returns the current time based on the system time and sets it to UTC. Clock clock = Clock.systemUTC(); System.out.println("Clock : " + clock); // Return time according to system clock area Clock defaultClock = Clock.systemDefaultZone(); System.out.println("Clock : " + clock); }
//How to judge whether a date is earlier or later than another date in Java public void isBeforeOrIsAfter(){ LocalDate today = LocalDate.now(); LocalDate tomorrow = LocalDate.of(2018, 1, 29); if(tomorrow.isAfter(today)){ System.out.println("Tomorrow comes after today"); } //Minus one day LocalDate yesterday = today.minus(1, ChronoUnit.DAYS); if(yesterday.isBefore(today)){ System.out.println("Yesterday is day before today"); } }
//Get the time below a specific time zone public void getZoneTime(){ //Set time zone ZoneId america = ZoneId.of("America/New_York"); LocalDateTime localtDateAndTime = LocalDateTime.now(); ZonedDateTime dateAndTimeInNewYork = ZonedDateTime.of(localtDateAndTime, america ); System.out.println("The current date and time are in a specific time zone : " + dateAndTimeInNewYork); }
//Use the YearMonth class to process specific dates public void checkCardExpiry(){ YearMonth currentYearMonth = YearMonth.now(); System.out.printf("Days in month year %s: %d%n", currentYearMonth, currentYearMonth.lengthOfMonth()); YearMonth creditCardExpiry = YearMonth.of(2028, Month.FEBRUARY); System.out.printf("Your credit card expires on %s %n", creditCardExpiry); }
//Check leap year public void isLeapYear(){ 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"); } }
//Calculate days and months between two dates public void calcDateDays(){ LocalDate today = LocalDate.now(); LocalDate java8Release = LocalDate.of(2018, Month.MAY, 14); Period periodToNextJavaRelease = Period.between(today, java8Release); System.out.println("Months left between today and Java 8 release : " + periodToNextJavaRelease.getMonths() ); }
public void ZoneOffset(){ LocalDateTime datetime = LocalDateTime.of(2018, Month.FEBRUARY, 14, 19, 30); ZoneOffset offset = ZoneOffset.of("+05:30"); OffsetDateTime date = OffsetDateTime.of(datetime, offset); System.out.println("Date and Time with timezone offset in Java : " + date); }
// Use predefined formatting tools to parse or format dates public void formateDate(){ String dayAfterTommorrow = "20180210"; LocalDate formatted = LocalDate.parse(dayAfterTommorrow, DateTimeFormatter.BASIC_ISO_DATE); System.out.printf("Date generated from String %s is %s %n", dayAfterTommorrow, formatted); }
package com.wq.study.java8.date; import java.time.Clock; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Month; import java.time.MonthDay; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.time.Period; import java.time.YearMonth; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.Date; public class DateTest { //Get today's date public void getCurrentDate(){ LocalDate today = LocalDate.now(); System.out.println("Today's Local date : " + today); //This is for comparison Date date = new Date(); System.out.println(date); } //Get the year, month and day information public void getDetailDate(){ LocalDate today = LocalDate.now(); int year = today.getYear(); int month = today.getMonthValue(); int day = today.getDayOfMonth(); System.out.printf("Year : %d Month : %d day : %d t %n", year, month, day); } //Process specific dates public void handleSpecilDate(){ LocalDate dateOfBirth = LocalDate.of(2018, 01, 21); System.out.println("The specil date is : " + dateOfBirth); } //Judge whether two dates are equal public void compareDate(){ LocalDate today = LocalDate.now(); LocalDate date1 = LocalDate.of(2018, 01, 21); if(date1.equals(today)){ System.out.printf("TODAY %s and DATE1 %s are same date %n", today, date1); } } //Processing recurring dates public void cycleDate(){ LocalDate today = LocalDate.now(); LocalDate dateOfBirth = LocalDate.of(2018, 01, 21); MonthDay birthday = MonthDay.of(dateOfBirth.getMonth(), dateOfBirth.getDayOfMonth()); MonthDay currentMonthDay = MonthDay.from(today); if(currentMonthDay.equals(birthday)){ System.out.println("Many Many happy returns of the day !!"); }else{ System.out.println("Sorry, today is not your birthday"); } } //Get current time public void getCurrentTime(){ LocalTime time = LocalTime.now(); System.out.println("local time now : " + time); } //Add hours public void plusHours(){ LocalTime time = LocalTime.now(); LocalTime newTime = time.plusHours(2); // Add two hours System.out.println("Time after 2 hours : " + newTime); } //How to calculate the date after one week public void nextWeek(){ LocalDate today = LocalDate.now(); LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS); System.out.println("Today is : " + today); System.out.println("Date after 1 week : " + nextWeek); } //Calculate the date before or after one year public void minusDate(){ LocalDate today = LocalDate.now(); LocalDate previousYear = today.minus(1, ChronoUnit.YEARS); System.out.println("Date before 1 year : " + previousYear); LocalDate nextYear = today.plus(1, ChronoUnit.YEARS); System.out.println("Date after 1 year : " + nextYear); } public void clock(){ // Returns the current time based on the system time and sets it to UTC. Clock clock = Clock.systemUTC(); System.out.println("Clock : " + clock); // Return time according to system clock area Clock defaultClock = Clock.systemDefaultZone(); System.out.println("Clock : " + clock); } //How to judge whether a date is earlier or later than another date in Java public void isBeforeOrIsAfter(){ LocalDate today = LocalDate.now(); LocalDate tomorrow = LocalDate.of(2018, 1, 29); if(tomorrow.isAfter(today)){ System.out.println("Tomorrow comes after today"); } LocalDate yesterday = today.minus(1, ChronoUnit.DAYS); if(yesterday.isBefore(today)){ System.out.println("Yesterday is day before today"); } } //Time zone processing public void getZoneTime(){ //Set time zone ZoneId america = ZoneId.of("America/New_York"); LocalDateTime localtDateAndTime = LocalDateTime.now(); ZonedDateTime dateAndTimeInNewYork = ZonedDateTime.of(localtDateAndTime, america ); System.out.println("The current date and time are in a specific time zone : " + dateAndTimeInNewYork); } //Use the YearMonth class to process specific dates public void checkCardExpiry(){ YearMonth currentYearMonth = YearMonth.now(); System.out.printf("Days in month year %s: %d%n", currentYearMonth, currentYearMonth.lengthOfMonth()); YearMonth creditCardExpiry = YearMonth.of(2028, Month.FEBRUARY); System.out.printf("Your credit card expires on %s %n", creditCardExpiry); } //Check leap year public void isLeapYear(){ 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"); } } //Calculate days and months between two dates public void calcDateDays(){ LocalDate today = LocalDate.now(); LocalDate java8Release = LocalDate.of(2018, Month.MAY, 14); Period periodToNextJavaRelease = Period.between(today, java8Release); System.out.println("Months left between today and Java 8 release : " + periodToNextJavaRelease.getMonths() ); } // Date and time with time difference information public void ZoneOffset(){ LocalDateTime datetime = LocalDateTime.of(2018, Month.FEBRUARY, 14, 19, 30); ZoneOffset offset = ZoneOffset.of("+05:30"); OffsetDateTime date = OffsetDateTime.of(datetime, offset); System.out.println("Date and Time with timezone offset in Java : " + date); } // Get timestamp public void getTimestamp(){ Instant timestamp = Instant.now(); System.out.println("What is value of this instant " + timestamp); } // Use predefined formatting tools to parse or format dates public void formateDate(){ String dayAfterTommorrow = "20180210"; LocalDate formatted = LocalDate.parse(dayAfterTommorrow, DateTimeFormatter.BASIC_ISO_DATE); System.out.printf("Date generated from String %s is %s %n", dayAfterTommorrow, formatted); } public static void main(String[] args) { DateTest dt = new DateTest(); dt.formateDate(); } } // Use predefined formatting tools to parse or format dates public void formateDate(){ String dayAfterTommorrow = "20180210"; LocalDate formatted = LocalDate.parse(dayAfterTommorrow, DateTimeFormatter.BASIC_ISO_DATE); System.out.printf("Date generated from String %s is %s %n", dayAfterTommorrow, formatted); }
summary
Java 8 date time API highlights:
Provided javax.time.ZoneId Gets the time zone.
The LocalDate and LocalTime classes are provided.
All date and time APIs in Java 8 are immutable and thread safe, whereas in the existing date and calendar APIs java.util.Date And SimpleDateFormat are non thread safe.
The main package is java.time , including some classes representing date, time and time interval. There are two bags in it java.time.format For formatting, java.time.temporal For lower level operations.
The time zone represents the standard time commonly used in an area of the earth. Each time zone has a code, usually in the format of Asia/Tokyo, plus the time difference from Greenwich or UTC. For example, the time difference in Tokyo is + 09:00.
[yunqi online class] product technology experts share every day!
Course address: https://yqh.aliyun.com/zhibo
Join the community immediately, face to face with experts, and keep abreast of the latest news of the course!
[yunqi online classroom community] https://c.tb.cn/F3.Z8gvnK
Original release time: June 19, 2020
By Wayfreem
This article comes from:“ Internet architect WeChat official account ”For more information, please pay attention to "[Internet architect]( https://mp.weixin.qq.com/s/wbC3OUYvJYMDPS-rVKVlww)