In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "how to use the thread-safe date class in Java8". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to use the thread-safe date class in Java8.
LocalDateTime
One of the new features of Java8, the new date class.
You often encounter time processing in the process of project development, but do you really use it correctly? do you understand that static modification SimpleDateFormat is disabled in Alibaba's development manual?
By reading this article, you will learn:
Why do you need LocalDate, LocalTime, LocalDateTime [new classes provided by java8]
Java8 the use of the new time API, including creation, formatting, parsing, calculation, modification
You can use Instant instead of Date,LocalDateTime instead of Calendar,DateTimeFormatter instead of SimpleDateFormat.
SimpleDateFormat thread is not safe
If Date is not formatted, the printed date is not readable.
Tue Sep 10 09:34:04 CST 2019
Use SimpleDateFormat to format time, but SimpleDateFormat is the format method of thread-unsafe SimpleDateFormat that ends up calling the source code:
Private StringBuffer format (Date date, StringBuffer toAppendTo, FieldDelegate delegate) {/ / Convert input date to time field list calendar.setTime (date); boolean useDateFormatSymbols = useDateFormatSymbols (); for (int I = 0; I
< compiledPattern.length; ) { int tag = compiledPattern[i] >> 8; int count = compiledPattern [iTunes +] & 0xff; if (count = = 255) {count = compiledPattern [iTunes +] it is expensive to create and destroy objects
Locking where format and parse methods are used = > thread blocking performance is poor
A better way to use ThreadLocal to ensure that each thread creates a SimpleDateFormat object at most once = >
Date is troublesome to deal with time, for example, if you want to get a certain year, a month, a week, and the time after n days, it is really too difficult to deal with it with Date. You may say that the Date class does not have such methods as getYear and getMonth. It is very Easy to get the year, month and day, but they are all abandoned.
Java8 new date and time API
When using the Java program to operate the database, we need to map the database type to the Java type. The following table shows the mapping of the database type to the old and new Java API:
Database corresponds to Java class (old) corresponds to Java class (new) DATETIMEjava.util.DateLocalDateTimeDATEjava.sql.DateLocalDateTIMEjava.sql.TimeLocalTimeTIMESTAMPjava.sql.TimestampLocalDateTimeLocalDate
Will only get the year, month and day.
/ / get the current year, month, day, LocalDate localDate = LocalDate.now (); / / construct the specified year, month, day, LocalDate localDate1 = LocalDate.of (2019, 9, 10); / / get the year, month, day, and day of the week int year = localDate.getYear (); int year1 = localDate.get (ChronoField.YEAR); Month month = localDate.getMonth () Int month2 = localDate.get (ChronoField.MONTH_OF_YEAR); int day = localDate.getDayOfMonth (); int day1 = localDate.get (ChronoField.DAY_OF_MONTH); DayOfWeek dayOfWeek = localDate.getDayOfWeek (); int dayOfWeek1 = localDate.get (ChronoField.DAY_OF_WEEK); LocalTime
Will only get a few minutes and seconds.
/ / create LocalTime LocalTime localTime = LocalTime.of (13,51,10); LocalTime localTime1 = LocalTime.now (); / / get hourly int hour = localTime.getHour (); int hour1 = localTime.get (ChronoField.HOUR_OF_DAY); / / get score int minute = localTime.getMinute (); int minute1 = localTime.get (ChronoField.MINUTE_OF_HOUR) / / get seconds int second = localTime.getSecond (); int second1 = localTime.get (ChronoField.SECOND_OF_MINUTE); LocalDateTime
Get the year, month, day, hour and second, which is equal to LocalDate+LocalTime
/ / create object LocalDateTime localDateTime = LocalDateTime.now (); LocalDateTime localDateTime1 = LocalDateTime.of (2019, Month.SEPTEMBER, 10, 14, 46, 56); / / LocalDate+LocalTime-- > LocalDateTime LocalDateTime localDateTime2 = LocalDateTime.of (localDate, localTime); LocalDateTime localDateTime3 = localDate.atTime (localTime); LocalDateTime localDateTime4 = localTime.atDate (localDate); / / get LocalDate LocalDate localDate2 = localDateTime.toLocalDate () / / get LocalTime LocalTime localTime2 = localDateTime.toLocalTime (); ZonedDateTime
LocalDateTime always represents a local date and time, and to represent a date and time with a time zone, we need ZonedDateTime.
You can simply think of ZonedDateTime as LocalDateTime plus ZoneId. ZoneId is a new time zone class introduced by java.time. Note that it is different from the old java.util.TimeZone.
Create a ZonedDateTime object
/ / default time zone ZonedDateTime zbj = ZonedDateTime.now (); / / use the specified time zone to get the current time ZonedDateTime zny = ZonedDateTime.now (ZoneId.of ("America/New_York"))
Results:
2019-09-15T20:58:18.786182+08:00 [Asia/Shanghai]
2019-09-15T08:58:18.788860-04:00 [America/New_York]
Another way to create it is to append a ZoneId to a LocalDateTime and become a ZonedDateTime:
LocalDateTime ldt = LocalDateTime.of (2019, 9, 15, 15, 16, 17); ZonedDateTime zbj = ldt.atZone (ZoneId.systemDefault ()); ZonedDateTime zny = ldt.atZone (ZoneId.of ("America/New_York"))
Time zone conversion
To convert the time zone, we first need to have a ZonedDateTime object, and then the associated time zone is converted to another time zone through withZoneSameInstant (), and the date and time are adjusted accordingly.
ZonedDateTime zbj = ZonedDateTime.now (ZoneId.of ("Asia/Shanghai")); / / converted to New York time: ZonedDateTime zny = zbj.withZoneSameInstant (ZoneId.of ("America/New_York"))
ZonedDateTime still provides addition and subtraction operations such as plusDays ().
In particular, when changing time zones, due to the existence of daylight saving time, the results of different dates are likely to be different. This is the result of the conversion on September 15 Beijing time:
2019-09-15T21:05:50.187697+08:00 [Asia/Shanghai]
2019-09-15T09:05:50.187697-04:00 [America/New_York]
This is the result of the conversion on November 15 Beijing time:
2019-11-15T21:05:50.187697+08:00 [Asia/Shanghai]
2019-11-15T08:05:50.187697-05:00 [America/New_York]
After the two conversions, New York time has a daylight saving time difference of 1 hour. When it comes to the time zone, do not calculate the time difference yourself, otherwise it will be difficult to handle daylight saving time correctly. With ZonedDateTime, it's easy to convert it to local time:
ZonedDateTime zdt =... LocalDateTime ldt = zdt.toLocalDateTime ()
When converted to LocalDateTime, the time zone information is discarded directly.
Instant
Get the number of seconds or timestamp
/ / create Instant object Instant instant = Instant.now (); / / get seconds long currentSecond = instant.getEpochSecond (); / / get milliseconds long currentMilli = instant.toEpochMilli (); long l = System.currentTimeMillis ()
System.currentTimeMillis () can also get milliseconds.
Date calculation
LocalDate, LocalTime, LocalDateTime and Instant are immutable objects. Modifying these objects will return a copy.
Increase or decrease the number of years, months, days, etc., take LocalDateTime as an example
/ / modify LocalDate, LocalTime, LocalDateTime, Instant LocalDateTime localDateTime = LocalDateTime.of (2019, Month.SEPTEMBER, 10, 14, 46, 56); / / add one year localDateTime = localDateTime.plusYears (1); localDateTime = localDateTime.plus (1, ChronoUnit.YEARS); / / decrease one month localDateTime = localDateTime.minusMonths (1); localDateTime = localDateTime.minus (1, ChronoUnit.MONTHS) / / modify some values through with / / change the year to 2020 localDateTime = localDateTime.withYear (2020); / / modify to 2022 localDateTime = localDateTime.with (ChronoField.YEAR, 2022); / / you can also modify month and day
Sometimes I want to know the date of the last day of this month and the date of the next weekend. API can get the answer quickly by providing the time and date.
LocalDate localDate = LocalDate.now (); LocalDate localDate1 = localDate.with (TemporalAdjusters.firstDayOfYear ())
For example, the first day of the current year is returned through firstDayOfYear (). There are many methods that are not illustrated here.
Formatting time
DateTimeFormatter provides a variety of formatting methods by default. If the default does not meet the requirements, you can create a custom formatting method through DateTimeFormatter's ofPattern method.
LocalDate localDate = LocalDate.of (2019, 9, 10); String S1 = localDate.format (DateTimeFormatter.BASIC_ISO_DATE); String S2 = localDate.format (DateTimeFormatter.ISO_LOCAL_DATE); / / Custom formatting DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern ("dd/MM/yyyy"); String S3 = localDate.format (dateTimeFormatter); parsing time
Compared with SimpleDateFormat, DateTimeFormatter is thread-safe
LocalDate localDate1 = LocalDate.parse ("20190910", DateTimeFormatter.BASIC_ISO_DATE); LocalDate localDate2 = LocalDate.parse ("2019-09-10", DateTimeFormatter.ISO_LOCAL_DATE); DateTimeFormatter instead of SimpleDateFormat
When using old Date objects, we use SimpleDateFormat to format the display. When using the new LocalDateTime or ZonedLocalDateTime, we need to use DateTimeFormatter to format the display.
Unlike SimpleDateFormat, DateTimeFormatter is not only immutable, it is also thread-safe. Because SimpleDateFormat is not thread-safe, when you use it, you can only create new local variables inside the method. On the other hand, DateTimeFormatter can only create one instance and quote it everywhere.
/ / Constructor 1: pass in format string DateTimeFormatter formatter = DateTimeFormatter.ofPattern ("yyyy-MM-dd HH:mm:ss"); / / Constructor 2: pass in format string and locale DateTimeFormatter formatter = DateTimeFormatter.ofPattern ("E, yyyy-MMMM-dd HH:mm:ss", Locale.US); DateTimeFormatter formatter = DateTimeFormatter.ofPattern ("E, yyyy-MMMM-dd HH:mm:ss", Locale.CHINA); DateTimeFormatter underlying principles
Is DateTimeFormatter thread-safe? Why?
Obviously, final modifies classes that are not inheritable, and final modifies variables to make immutable classes, similar to String, not only thread-safe but also efficient. Globally, there can be only one object and multiple thread references.
Thread-safe alternatives for format and parse
Using the format and parse methods of LocalDateTime, passing in the corresponding DateTimeFormatter object parameters is actually calling the format and parse methods of DateTimeFormatter to format and parse the date, which is thread-safe.
The DateTimeFormatter class parses the date variable in LocalDateTime and returns it as StringBuilder. LocalDateTime and other new date classes are all final-modified classes and cannot be inherited, and the corresponding date variables are final-modified, that is, immutable classes. After one assignment, it is immutable, and there is no multithreaded data problem.
At this point, I believe you have a deeper understanding of "how to use the thread-safe date class in Java8". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.