**
Time formatting LocalDate,DateTimeFormatter - > parse, ofparttern
**
**Instant: * * instant instance.
**LocalDate: * * local date, excluding specific time. For example, January 14, 2014 can be used to record birthdays, anniversaries, joining dates, etc.
**LocalTime: * * local time, excluding date.
**LocalDateTime: * * combines date and time, but does not contain time difference and time zone information.
**ZonedDateTime: * * the most complete date and time, including the time zone and the 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 for parsing and formatting time is also redesigned
usage method:
public static final DateTimeFormatter YYYYMMDD_PATTERN_FORMARTTER = DateTimeFormatter .ofPattern("yyyyMMdd"); public static final DateTimeFormatter YYYY_MM_DD_PATTERN_FORMARTTER = DateTimeFormatter .ofPattern("yyyy_MM_dd"); public static final DateTimeFormatter YYYYMMDDHHMMSS_PATTERN_FORMARTTER = DateTimeFormatter .ofPattern("yyyyMMddHHmmss"); public static final DateTimeFormatter YYYY_MM_DD_HH_MM_SS_PATTERN_FORMARTTER = DateTimeFormatter .ofPattern("yyyy_MM_dd HH:mm:ss"); //Converts a "yyyy_MM_dd" format string to a "yyyyMMdd" format string private String getDateString(String str){ LocalDate parse = **LocalDate**.parse(str, YYYY_MM_DD_PATTERN_FORMARTTER); String format = parse.format (YYYYMMDD_PATTERN_FORMARTTER ); return format ; } //Converts the "yyyy_MM_dd HH:mm:ss" format string to the "yyyyMMddHHmmss" format string private String getDateString(String str){ LocalDate parse = **LocalDateTime**.parse(str, YYYY_MM_DD_HH_MM_SS_PATTERN_FORMARTTER ); String format = parse.format(YYYYMMDDHHMMSS_PATTERN_FORMARTTER ); return format ; } //Converts a "yyyyMMdd" format string to a "yyyy_MM_dd" format string private String getDateString(String str){ LocalDate parse = **LocalDate**.parse(str, YYYYMMDD_PATTERN_FORMARTTER ); String format = parse.format (YYYY_MM_DD_PATTERN_FORMARTTER); return format ; } //Converts the "yyyyMMddHHmmss" format string to the "yyyy_MM_dd HH:mm:ss" format string private String getDateString(String str){ LocalDate parse = **LocalDateTime**.parse(str, YYYYMMDDHHMMSS_PATTERN_FORMARTTER ); String format = parse.format(YYYY_MM_DD_HH_MM_SS_PATTERN_FORMARTTER ); return format ; }
API usage:
public class TimeTest { public static void main(String[] args) { //Get current time LocalDate today = LocalDate.now(); System.out.println("localDate:"+today); //output:localDate:2021-10-26 //Obtain year, month and day information 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); //output: Year : 2021 Month : 10 day : 26 t //The factory method LocalDate.of() creates an arbitrary date LocalDate dateOfBirth = LocalDate.of( 2021 , 10 , 26); System.out.println( "create dateOfBirth is : " + dateOfBirth); //output: create dateOfBirth is : 2021-10-26 //Judge whether the two dates are equal. If the compared date is of character type, it needs to be parsed into a date object before judgment LocalDate date1 = LocalDate.of( 2021, 10 , 26 ); if (date1.equals(today)){ System.out.printf( "Today %s and date1 %s are same date %n" , today, date1); } //output:Today 2021-10-26 and date1 2021-10-26 are same date //Check for recurring events through MonthDay MonthDay birthday = MonthDay.of(dateOfBirth.getMonth(), dateOfBirth.getDayOfMonth()); MonthDay currentMonthDay = MonthDay.from(today); if (currentMonthDay.equals(birthday)){ System.out.println( "happy birthday !!!" ); } else { System.out.println( "Sorry, today is not your birthday" ); } //output:happy birthday !!! //The LocalTime class is used to obtain the time. The default format is hh:mm:ss:nnn LocalTime time = LocalTime.now(); System.out.println( "local time now : " + time); //output:local time now : 17:10:52.862 //Add 2 hours to the existing time LocalTime newTime = time.plusHours( 2 ); System.out.println( "Time after 2 hours : " + newTime); //output:Time after 2 hours : 19:10:52.862 //Calculate the date after one week LocalDate nextWeek = today.plus( 1 , ChronoUnit.WEEKS); System.out.println( "Today is : " + today); //output:Today is : 2021-10-26 System.out.println( "Date after 1 week : " + nextWeek); //output:Date after 1 week : 2021-11-02 //Calculate the date one year ago or one year later LocalDate previousYear = today.minus( 1 , ChronoUnit.YEARS); System.out.println( "Date before 1 year : " + previousYear); //output:Date before 1 year : 2020-10-26 LocalDate nextYear = today.plus( 1 , ChronoUnit.YEARS); System.out.println( "Date after 1 year : " + nextYear); //output:Date after 1 year : 2022-10-26 //Clock class is used to obtain the current time stamp or date and time information in the current time zone // Clock can be used to replace System.currentTimeInMillis() and TimeZone.getDefault(). Clock clock = Clock.systemUTC(); System.out.println( "Clock : " + clock); //output:Clock : SystemClock[Z] Clock defaultClock = Clock.systemDefaultZone(); System.out.println( "defaultClock : " + defaultClock); //output:defaultClock : SystemClock[Asia/Shanghai] //Determine whether the date is before or after another date LocalDate tomorrow = LocalDate.of( 2022 , 1 , 15 ); if (tomorrow.isAfter(today)){ System.out.println( "Tomorrow comes after today" ); } LocalDate yesterday = today.minus( 1 , DAYS); if (yesterday.isBefore(today)){ System.out.println( "Yesterday is day before today" ); } //output:Tomorrow comes after today //output:Yesterday is day before today //ZoneId is used to process a specific time zone, and ZoneDateTime class is used to represent the time in a time zone 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); //output:Current date and time in a particular timezone : 2021-10-26T17:10:52.866-04:00[America/New_York] //YearMonth: used to indicate credit card expiration date, FD expiration date, futures option expiration date, etc. // You can also use this class to get the total number of days in the current month. The lengthOfMonth() method of the YearMonth instance can return the number of days in the current month YearMonth currentYearMonth = YearMonth.now(); System.out.printf( "Days in month year %s: %d%n" , currentYearMonth, currentYearMonth.lengthOfMonth()); //output:Days in month year 2021-10: 31 YearMonth creditCardExpiry = YearMonth.of( 2018 , Month.FEBRUARY); System.out.printf( "Your credit card expires on %s %n" , creditCardExpiry); //output:Your credit card expires on 2018-02 //Check leap year if (today.isLeapYear()){ System.out.println( "This year is Leap year" ); } else { System.out.println( "2014 is not a Leap year" ); } //output:2014 is not a Leap year //Calculate the number of days and months between two dates: calculate the number of months between the current day and a future day LocalDate future = LocalDate.of( 2022 , Month.MARCH, 14 ); Period periodToNextJavaRelease = Period.between(today, future); System.out.println( "Months left between today and future : " + periodToNextJavaRelease.getMonths() ); //output:Months left between today and future : 4 //ZoneOffset class is used to represent the time zone. For example, the difference between India and GMT or UTC standard time zone is + 05:30, // You can obtain the corresponding time zone through the ZoneOffset.of() static method. // Once the time difference is obtained, you can create an OffSetDateTime object by passing in LocalDateTime and ZoneOffset LocalDateTime datetime = LocalDateTime.of( 2014 , Month.JANUARY, 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); //output:Date and Time with timezone offset in Java : 2014-01-14T19:30+05:30 //Get the current timestamp, which is equivalent to the Date class before Java 8 Instant timestamp = Instant.now(); System.out.println( "What is value of this instant " + timestamp); //output:What is value of this instant 2021-10-26T09:10:52.873Z //Convert Instant to java.util.Date Date date2 = Date.from(timestamp); System.out.println( "date2 :" + timestamp); //output:date2: 2021-10-26T09:10:52.873Z //Convert Date class to Instant class Instant instant = date2.toInstant(); System.out.println( "instant: " + timestamp); //output:instant :2021-10-26T09:10:52.873Z //Use predefined formatting tools to parse or format the date: "20140116" -- > "2014-01-16" String dayAfterTommorrow = "20140116" ; LocalDate formatted = LocalDate.parse(dayAfterTommorrow, DateTimeFormatter.BASIC_ISO_DATE); System.out.printf( "Date generated from String %s is %s %n" , dayAfterTommorrow, formatted); //output:Date generated from String 20140116 is 2014-01-16 //Resolving dates using custom formatting tools String goodFriday = "Apr 18 2014" ; try { DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MMM dd yyyy" ); LocalDate holiday = LocalDate.parse(goodFriday, formatter); System.out.printf( "Successfully parsed String %s, date is %s%n" , goodFriday, holiday); } catch (DateTimeParseException ex) { System.out.printf( "%s is not parsable!%n" , goodFriday); ex.printStackTrace(); } //Output :Successfully parsed String Apr 18 2014, date is 2014-04-18 //Convert date to string LocalDateTime arrivalDate = LocalDateTime.now(); try { DateTimeFormatter format = DateTimeFormatter.ofPattern( "MMM dd yyyy hh:mm a" ); String landing = arrivalDate.format(format); System.out.printf( "Arriving at : %s %n" , landing); } catch (DateTimeException ex) { System.out.printf( "%s can't be formatted!%n" , arrivalDate); ex.printStackTrace(); } //Output : Arriving at : Jan 14 2014 04:33 PM } //You can also compare clock clocks, such as the following example: //This method is very useful when dealing with dates in different time zones public class MyClass { private Clock clock; // dependency inject public void process(LocalDate eventDate) { if (eventDate.isBefore(LocalDate.now(clock))){ System.out.println("....."); } } } }
Summary:
1) javax.time.ZoneId is provided to obtain the time zone.
2) LocalDate and LocalTime classes are provided.
3) All Date and time APIs in Java 8 are immutable classes and thread safe, while java.util.Date and SimpleDateFormat in the existing Date and calendar APIs are non thread safe.
4) The main package is Java. Time, which contains some classes representing date, time and time interval. There are two sub packages java.time.format for formatting and java.time.temporary for lower level operations.
5) The time zone represents the standard time commonly used in an area of the earth. Each time zone has a code. The format is usually composed of region / city (Asia/Tokyo), plus the 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. It is used to represent the complete date (year, month, day) and time (hour, minute, second, nanosecond) information including the time difference from Greenwich or UTC.
7) The DateTimeFormatter class is used to format and parse time. Unlike SimpleDateFormat, this class is immutable and thread safe. Static constants can be assigned when necessary. The DateTimeFormatter class provides a large number of built-in formatting tools and allows you to customize them. In terms of conversion, parse() is also provided to parse the string into a date. If there is an error in parsing, a DateTimeParseException will be thrown. The DateTimeFormatter class also has format() to format the date. If there is an error, a DateTimeException will be thrown.
8) In addition, 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 will throw exceptions when parsing "Jan 2 2014", because the second format requires that the date must be two digits. If you want to correct, you must fill in zero in front of the date when there are only single digits, that is, "Jan 2 2014" should be written as "Jan 02 2014".
reference resources:
https://blog.csdn.net/weixin_34010566/article/details/94685511