In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
I believe many inexperienced people are at a loss about what the date and time object in the new feature of Java8 is. Therefore, this article summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.
Date time object
There are two types of operations about date and time:
Conversion: conversion to string, conversion to timestamp calculation: calculation of the interval between two time points, calculation of time points and time periods (next week N, next month D, last year M month D, etc.)
Java8 provides three classes: LocalDate, LocalTime, and LocalDateTime in the form of 2020-01-01, 12:30:00, 2020-01-01 12:30:00
Create object
The method of getting a class object is very simple.
LocalDate now = LocalDate.now (); LocalDate ld = LocalDate.of (2019, 1, 1); / / get year, month and day now.getYear (); now.getMonthValue (); / / if you call now.getMonth (), it will return to you an uppercase English month word now.getDayOfMonth (); / / the name should mean getDayOfWeek (); getDayOfYear (); / / set year, month and day LocalDate ld1 = month (2021) / / 2021-01-01LocalDate ld2 = ld.withMonth (12); / 2019-12-01LocalDate ld3 = ld.withDayOfMonth (12); / 2019-12-12 set / you may wonder, since it is a setting, why not use the word set, but use with// because the set operation generally changes the calling object itself and has no return value / / while with creates a new object based on the calling object, sets the value and returns without changing the calling object / / if you are the child who broke the casserole, you may ask: why can't you change the calling object? / / because LocalDate is modified by final (final is called the knife of the Java) / / from a physical point of view, humans cannot change time (travel) / / if you have an anti-human calendar operation like ld.withMonth (13), of course you will throw an exception.
Both LocalTime and LocalDateTime have methods similar to LocalDate, so I won't list them one by one (because I feel more and more like an api document).
Java8 API official documents through train
Conversion
Conversion between date-time objects and strings:
/ / LocalDateTime object-> string DateTimeFormatter dtf = DateTimeFormatter.ofPattern ("yyyy-MM-dd HH:mm:ss"); LocalDateTime now = LocalDateTime.now (); String dateTimeStr = now.format (dtf); System.out.println (dateTimeStr); / / string-> LocalDateTime object String str = "2022-01-30 12:15:20"; LocalDateTime dateTime = LocalDateTime.parse (str, dtf); System.out.println (dateTime)
The DateTimeFormatter class also provides some off-the-shelf formatter, such as
DateTimeFormatter.BASIC_ISO_DATE = > DateTimeFormatter.ofPattern ("yyyyMMdd") DateTimeFormatter.ISO_LOCAL_DATE = = > DateTimeFormatter.ofPattern ("yyyy-MM-dd") / / more formatter can be queried in api documents
The essence of learning is not what to remember, but what it triggers your thinking. -- Michael Sandel
Conversion between date, time and timestamp:
/ / LocalDateTime object-> timestamp LocalDateTime now = LocalDateTime.now (); / / get system default time zone ZoneId systemDefaultZoneId = ZoneId.systemDefault (); Instant instant = now.atZone (systemDefaultZoneId). ToInstant (); long timestamp = instant.toEpochMilli (); System.out.println (timestamp); / / timestamp-> LocalDateTime object long timestamp2 = 1578919583784L Instant instant2 = Instant.ofEpochMilli (timestamp2); LocalDateTime dateTime2 = LocalDateTime.ofInstant (instant2, systemDefaultZoneId); System.out.println (dateTime2)
"I don't understand why the timestamp is so troublesome!"
In addition: the conversion between java.util.Date and java.time.LocalDateTime needs to be implemented through Instant, neither of which provides a direct conversion method
/ / get system default time zone ZoneId systemDefaultZoneId = ZoneId.systemDefault (); / / Date to LocalDateTimeDate date3 = new Date (); Instant instant3 = date3.toInstant (); LocalDateTime localDateTime3 = LocalDateTime.ofInstant (instant3, systemDefaultZoneId); / / LocalDateTime to DateInstant instant4 = now.atZone (systemDefaultZoneId). ToInstant (); Date date4 = Date.from (instant4)
Also: LocalDateTime can be made up of LocalDate and LocalTime, or split into the two
LocalDate nowLocalDate = LocalDate.now (); LocalTime nowLocalTime = LocalTime.now (); LocalDateTime nowLocalDateTime = LocalDateTime.of (nowLocalDate, nowLocalTime); nowLocalDateTime.toLocalDate (); nowLocalDateTime.toLocalTime ()
Calculate
Calculate the interval between a time point and a time point:
/ / calculate the interval between dates and times LocalTime startTime = LocalTime.now (); LocalTime endTime = startTime.plusHours (1) .plusMinutes (50); Duration duration = Duration.between (startTime, endTime); / / interval seconds duration.getSeconds (); / / interval days duration.toDays (); / / interval hours duration.toHours (); / / interval minutes duration.toMinutes ()
The parameters of Duration.between (start, end) can be LocalDateTime, LocalTime
It only returns an integer (the integer after the decimal is rounded out, which is equivalent to floor ()), but not one hour and 50 minutes. If you want the form of y years, M months, d days, H hours, m minutes, s seconds, maybe you can assemble it yourself.
/ / the interval between calculated dates LocalDate startDate = LocalDate.now (); LocalDate endDate = LocalDate.of (2031, 1, 1); Period pe = Period.between (startDate, endDate); pe.getYears (); pe.getMonths (); pe.getDays ()
Calculation of time points and time periods:
Public LocalDateTime plusYears (long years) {LocalDate newDate = date.plusYears (years); return with (newDate, time);} public LocalDateTime plusMonths (long months) {LocalDate newDate = date.plusMonths (months); return with (newDate, time);} public LocalDateTime plusWeeks (long weeks) {LocalDate newDate = date.plusWeeks (weeks); return with (newDate, time);} public LocalDateTime plusDays (long days) {LocalDate newDate = date.plusDays (days); return with (newDate, time) } public LocalDateTime plusHours (long hours) {return plusWithOverflow (date, hours, 0,0,0,1);} public LocalDateTime plusMinutes (long minutes) {return plusWithOverflow (date, 0, minutes, 0,0,1);} public LocalDateTime plusSeconds (long seconds) {return plusWithOverflow (date, 0,0, seconds, 0,1);} public LocalDateTime plusNanos (long nanos) {return plusWithOverflow (date, 0,0,0, nanos, 1);} public LocalDateTime minusYears (long years) {return (years = = Long.MIN_VALUE? PlusYears (Long.MAX_VALUE) .plusYears (1): plusYears (- years);} public LocalDateTime minusMonths (long months) {return (months = = Long.MIN_VALUE? PlusMonths (Long.MAX_VALUE) .plusMonths (1): plusMonths (- months);} public LocalDateTime minusWeeks (long weeks) {return (weeks = = Long.MIN_VALUE? PlusWeeks (Long.MAX_VALUE) .plusWeeks (1): plusWeeks (- weeks);} public LocalDateTime minusDays (long days) {return (days = = Long.MIN_VALUE? PlusDays (Long.MAX_VALUE) .plusDays (1): plusDays (- days);} public LocalDateTime minusHours (long hours) {return plusWithOverflow (date, hours, 0,0,0,-1);} public LocalDateTime minusMinutes (long minutes) {return plusWithOverflow (date, 0, minutes, 0,0,-1);} public LocalDateTime minusSeconds (long seconds) {return plusWithOverflow (date, 0,0, seconds, 0,-1) } public LocalDateTime minusNanos (long nanos) {return plusWithOverflow (date, 0,0,0, nanos,-1);}
See, there are years, months, days, hours, minutes, seconds and milliseconds.
Use it as much as you want, for a small example:
LocalDateTime now = LocalDateTime.now (); / / 30 years later (I have to go to work and haven't retired) LocalDateTime after30Years = now.plusYears (30L); System.out.println (after30Years); / / 347 months later (I can pay off the ╥ loans ╥) LocalDateTime after348Months = now.plusMonths (347L); System.out.println (after348Months); / / 11 days later (New Year's Eve) LocalDateTime after10Days = now.plusDays (10L); System.out.println (after10Days) / / 8 hours ago (I was at work) LocalDateTime before8Hours = now.minusHours (8L); System.out.println (before8Hours); / / 3 minutes ago (I started listening to Let it go) LocalDateTime before3Before = now.minusMinutes (3L); System.out.println (before3Before); / / 10 seconds ago (write the following code) LocalDateTime before10Second = now.minusSeconds (10L); System.out.println (before10Second)
In fact, there is no need to distinguish between addition and subtraction, you can also use plusXxx to do subtraction, as long as you pass in negative parameters
In addition, there is another type of demand, such as:
When is Thanksgiving next year? (the fourth Thursday in November is Thanksgiving) what day is next Friday?
This is going to use the time corrector TemporalAdjuster. Let me first introduce TemporalAdjuster, which is a functional interface with only one method adjustInto.
@ FunctionalInterfacepublic interface TemporalAdjuster {Temporal adjustInto (Temporal temporal);}
Temporal is an interface, and LocalDateTime, LocalDate and LocalTime are all its implementation classes.
There is a with (TemporalAdjuster adjuster) method in LocalDateTime, LocalDate, and LocalTime to implement the alternative requirements mentioned above.
/ / next Friday LocalDateTime now = LocalDateTime.now (); LocalDateTime nextFriday = now.with (dt-> {/ / dt is the `Temporal` object, but essentially the calling object LocalDateTime dateTime = (LocalDateTime) dt; / / it's a pity that there is no withDayOfWeek () method, otherwise it would be very convenient for int dayOfWeekValue = dateTime.getDayOfWeek (). GetValue (); int fridayValue = DayOfWeek.FRIDAY.getValue (); return dateTime.plusWeeks (1L) .plusDays (fridayValue-dayOfWeekValue);}) System.out.println (nextFriday); / / next year's Thanksgiving (the fourth Thursday in November) LocalDate thanksGivingDay = LocalDate.now (). With (t-> {LocalDate d = (LocalDate) t; / / LocalDate newDate = d.plusYears (1L). WithMonth (11). WithDayOfMonth (1); int dayOfWeekValue = newDate.getDayOfWeek (). GetValue (); int thursdayValue = DayOfWeek.THURSDAY.getValue (); long plusWeeks = dayOfWeekValue > thursdayValue? 4L: 3L Return newDate.plusWeeks (plusWeeks) .plusDays (thursdayValue-dayOfWeekValue);}); System.out.println (thanksGivingDay)
In fact, TemporalAdjusters provides a lot of TemporalAdjuster objects, just like Collectors is to Collector in the previous Stream.
The above requirements can be easily realized by using TemporalAdjusters.
/ next Friday LocalDateTime nextFriday = LocalDateTime.now (). With (TemporalAdjusters.next (DayOfWeek.FRIDAY)); System.out.println (nextFriday); / / next year's Thanksgiving (the fourth Thursday in November) LocalDate date = LocalDate.now () .plusYears (1L) .withMonth (11); LocalDate thanksGivingDay = date.with (TemporalAdjusters.dayOfWeekInMonth (4, DayOfWeek.THURSDAY)); System.out.println (thanksGivingDay)
Note: the TemporalAdjusters.next (DayOfWeek day) method returns the next Friday, not the next Friday as we generally understand, for example: today's 2020-01-13 (Monday), then the return is the Friday of 2020-01-17 four days later.
In addition, TemporalAdjusters provides not only the above two methods, but also many other methods, and there are enough examples in the API documentation to understand at a glance.
Students who are interested are advised to read some source code, refer to the Java8 code logic, and then use other programming languages to implement the same date-time operation, because date-time operations are often used in other programming (such as javaScript).
Other characteristics
Listing them means I know them, but it doesn't mean I understand them, so Let It Go!
The default method in the interface
Static methods in the interface
Optional class
Optional op = Optional.of (str)
It is used to indicate that the variable may be empty.
If a variable is likely to be empty, we must determine whether it is empty or not every time we use it before Java8. It still is!
Optional does not avoid null pointer exceptions, simply indicating that the identity variable may be null. For example:
Mines were planted on the road ahead, but it could not be seen from the surface that unless we tried to throw stones at every step, we could not tell which step would explode. And Optional is used to identify the location of mines. If we know where there is a mine, we will go around it so that we can pass through safely.
In addition, Optional also provides a function to set default values, which is fun.
Before Integer pageSize = null;//, we set the default value / / pageSize = pageSize = = null? 10: pageSize;//System.out.println (pageSize); / / use Optional to set the default value pageSize = Optional.ofNullable (pageSize) .orElse (20); System.out.println (pageSize); / / Custom default Integer defaultPageSize = Optional.ofNullable (pageSize) .orElseGet (()-> {return new Integer (50);})
Conclusion
This is the end of Java8's new feature series.
The most important thing is to read more Java official API documents!
I was thinking maybe we were overcorrected. The most common answer for all kinds of technology groups is: ask Baidu! Does Baidu know everything?!
To tell you the truth, in today's era, individuals can publish articles and comments on the Internet, and then we can reprint each other, false can become true! Reproduced without verification; valid at that time and now out of date; casually reprinted with a link in the article. meet the eye everywhere
After reading the above, have you mastered the method of what the date-time object is in Java8's new features? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.