Don't use jodatime any more! The most authoritative java 8 date and time classes in the whole network: detailed explanation of localdate and localdatetime

JavaEdge 2021-02-23 13:27:47
don use jodatime authoritative java


1 Why a new date and time library is needed ?

Java A long-term worry for developers is the lack of support for ordinary developers' date and time use cases .

for example , Existing classes ( for example java.util.Date and SimpleDateFormatter) It's not thread safe , This leads to potential concurrency problems for users , This is not a problem that the average developer would expect to deal with when writing date handling code . Some date and time classes also show fairly poor API Design . for example , year java.util.Date from 1900 Start , Month from 1 Start , Tiancong 0 Start , It's not very intuitive .

These and other issues lead to third-party date and time libraries ( for example Joda-Time) The prosperity of .

In order to solve these problems and in JDK Better support in the kernel , in the light of Java SE 8 Designed a new date and time without these problems API. The project consists of Joda-Time(Stephen Colebourne) and Oracle Author of JSR 310 Under common leadership , Appear in the Java SE 8 In the package java.time.

2 The core idea

Immutable value classes

Java One of the serious drawbacks of existing formatters is that they are not thread safe . This puts a burden on developers , Make them need to use them in a thread safe way and consider concurrency in their daily processing of date processing code . new API Avoid this problem by ensuring that all of its core classes are immutable and represent well-defined values .

Domain Driven Design

new API The model and the class domain representing different use cases are very precise Date and Time Tight . This is different from the previous Java Library is different , The latter is poor in this respect . for example ,java.util.Date Represent a moment on the timeline ( One self UNIX Millisecond wrappers since the beginning of the Millennium ), But if you call toString(), It turns out that it has time zones , This leads to confusion among developers .

This emphasis on Domain Driven Design offers long-term benefits in terms of clarity and intelligibility , But from the previous API Migration to Java SE 8 when , You may need to consider the application's domain date model .

Separated in chronological order

new API So that people can use different calendar systems to meet certain areas of the world ( Like Japan or Thailand ) User needs , And these users don't necessarily follow ISO-8601. This will not put an extra burden on most developers , They just need to use a standard chronology .

3 LocalDate、LocalTime、LocalDateTime

3.1 comparison Date The advantages of

  • Date and SimpleDateFormatter Non-thread safety , and LocalDate and LocalTime and String equally , yes final type - Thread safe and cannot be modified .
  • Date Month from 0 Start , January is 0, December is 11.LocalDate Month and week have been changed to enum , No more mistakes .
  • Date It's a “ Universal interface ”, It contains the date 、 Time , And milliseconds . If you only need a date or time, it's useless to have some data . In the new Java 8 in , The date and time are clearly divided into LocalDate and LocalTime,LocalDate Can't contain time ,LocalTime Cannot include date . Of course ,LocalDateTime To include both date and time .
  • Date Reckoning time ( For example, push forward a few days / Put it back a few days / Calculate whether a year is a leap year / Calculate the first day of a month or a year 、 The last day 、 The first Monday and so on ) To combine Calendar A lot of code to write , It's disgusting !

Both are local , Because they represent the date and time from the observer's point of view , For example, the calendar on the desk or the clock on the wall .

There is also a class called a composite class LocalDateTime, This is a LocalDate and LocalTime Pairing of .

Time zones distinguish the context of different observers , Put it aside here ; When context is not needed , You should use these local classes . These classes can even be used to represent time on a distributed system with a consistent time zone .

Commonly used API

now()

Gets the current date in the default time zone system clock . This method will query the system clock in the default time zone , To get the current date . Using this method will prevent the use of the backup clock for testing , Because the clock is hard coded .

Convenient addition and subtraction , You don't have to figure it out !

plusMonths

Return this copy LocalDate Added a specified number of months . This method will specify the months fields of the amount in three steps :

  • Add the number of months entered to month-of-year Field
  • Check whether the result date is invalid
  • adjustment day-of-month , If necessary, the last valid date

for example ,2007-03-31 Adding one month will result in invalid dates 2007 year 4 month 31 Japan . Not returning an invalid result , It is 2007-04-30 It's the last valid date . The immutability of the calling instance is not affected by the method .

4 Create objects

Factory method

new API All the core classes in are constructed through skilled factory methods .

  • When a value is constructed by its constituent field , It's called a factory of
  • When converting from another type , The factory is called from
  • There are also parsing methods that take strings as parameters .

getter Appointment

  • In order to learn from Java SE 8 Class gets the value , Standard... Is used Java getter Appointment , as follows :

Change the object value

You can also change object values to perform calculations . Because of the new API All core classes in are immutable , So these methods will be called with And return the new object , Instead of using setter. There are also calculation methods based on different fields .

an adjuster

new API There's also the concept of a regulator — A block of code , It can be used to package general processing logic . You can write a WithAdjuster, Used to set one or more fields , You can also write a PlusAdjuster Used to add or subtract certain fields . Value classes can also act as regulators , under these circumstances , They will update the values of the fields they represent . The built-in regulator is made up of new API Definition , But if you have specific business logic that you want to reuse , You can write your own regulator .

import static java.time.temporal.TemporalAdjusters.*;
LocalDateTime timePoint = ...
foo = timePoint.with(lastDayOfMonth());
bar = timePoint.with(previousOrSame(ChronoUnit.WEDNESDAY));
// Use value classes as adjusters
timePoint.with(LocalTime.now()); 

5 truncation

new API By providing a date , Time and date with time types to support different precision time points , But obviously , The concept of precision is higher than that .

The truncatedTo Methods exist to support this use , It can truncate your values to fields , as follows

LocalTime truncatedTime = time.truncatedTo(ChronoUnit.SECONDS);

6 The time zone

The local class we looked at earlier abstracts the complexity introduced by time zones . Time zones are a set of rules , Corresponding to the same area of standard time . There are about 40 individual . Time zones are defined by their relation to coordinated universal time (UTC,Coordinated Universal Time) The offset definition of . They move roughly in sync , But there are some differences .

The time zone can be represented by two identifiers : abbreviation , for example “ PLT”, Longer, for example “ Asia / Karachi”. When designing an application , You should consider which case is suitable to use time zone , When do I need an offset .

  • ZoneId Is the identifier of the zone . Every ZoneId Rules correspond to some rules , These rules define the time zone of the location . When designing software , If you consider using something like “ PLT” or “ Asia / Karachi” Strings like that , Instead, use the domain class . An example use case is to store users' preferences for their time zones .
  • ZoneOffset It's Greenwich / UTC Time periods that differ from time zones . Can be in specific ZoneId, Parsed at a specific time , Like the list 7 Shown .
ZoneOffset offset = ZoneOffset.of("+2:00");

7 Time zone class

ZonedDateTime Is a date and time with a fully qualified time zone . This can solve any point in time offset . Best practices : To represent a date and time independent of the context of a particular server , You should use ZonedDateTime.

ZonedDateTime.parse("2007-12-03T10:15:30+01:00[Europe/Paris]");

OffsetDateTime Is the date and time with resolved offset . This is useful for serializing data into a database , If the server is in a different time zone , Should also be used as a serialization format for recording timestamps .

OffsetTime Is the time with a definite offset , as follows :

OffsetTime time = OffsetTime.now();
// changes offset, while keeping the same point on the timeline
OffsetTime sameTimeDifferentOffset = time.withOffsetSameInstant(
offset);
// changes the offset, and updates the point on the timeline
OffsetTime changeTimeWithNewOffset = time.withOffsetSameLocal(
offset);
// Can also create new object with altered fields as before
changeTimeWithNewOffset
.withHour(3)
.plusSeconds(2);
OffsetTime time = OffsetTime.now();
// changes offset, while keeping the same point on the timeline
OffsetTime sameTimeDifferentOffset = time.withOffsetSameInstant(
offset);
// changes the offset, and updates the point on the timeline
OffsetTime changeTimeWithNewOffset = time.withOffsetSameLocal(
offset);
// Can also create new object with altered fields as before
changeTimeWithNewOffset
.withHour(3)
.plusSeconds(2);

Java There is already a time zone class in ,java.util.TimeZone but Java SE 8 Not using it , Because all JSR 310 Classes are immutable and time zones are variable .

8 Period of time (period)

Period For example “ 3 One month and one day ” Value , It's the distance on the timeline . This is in sharp contrast to the other classes we've discussed so far , They're the focus of the timeline .

// 3 year , 2 month , 1 God
Period period = Period.of(3, 2, 1);
// Use period Modify the date value
LocalDate newDate = oldDate.plus(period);
ZonedDateTime newDateTime = oldDateTime.minus(period);
// Components of a Period are represented by ChronoUnit values
assertEquals(1, period.get(ChronoUnit.DAYS));
// 3 years, 2 months, 1 day
Period period = Period.of(3, 2, 1);
// You can modify the values of dates using periods
LocalDate newDate = oldDate.plus(period);
ZonedDateTime newDateTime = oldDateTime.minus(period);
// Components of a Period are represented by ChronoUnit values
assertEquals(1, period.get(ChronoUnit.DAYS)); 

9 The duration of the (Duration)

Duration It's the distance measured by time on the timeline , It achieves a similar purpose to Period, But the accuracy is different :

// 3 s and 5 ns Of Duration
Duration duration = Duration.ofSeconds(3, 5);
Duration oneDay = Duration.between(today, yesterday);
// A duration of 3 seconds and 5 nanoseconds
Duration duration = Duration.ofSeconds(3, 5);
Duration oneDay = Duration.between(today, yesterday);

It can be done to Duration The instance performs the normal addition , Subtract and “ with” operation , You can also use values that modify the date or time Duration.

10 Chronology

In order to meet the needs of using non ISO The requirements of calendar system developers ,Java SE 8 Introduced Chronology, On behalf of the calendar system , And act as a time point factory in the calendar system . There are also some interfaces corresponding to core point in time classes , But through

Chronology:
ChronoLocalDate
ChronoLocalDateTime
ChronoZonedDateTime
Chronology:
ChronoLocalDate
ChronoLocalDateTime
ChronoZonedDateTime

These classes are only suitable for developers who are developing highly internationalized applications and need to consider the local calendar system , Developers without these requirements should not use them . Some calendar systems don't even have the concept of a month or a week , So you need to go through very general fields API Calculate .

11 The rest API

Java SE 8 There are also classes with other common use cases . There is one MonthDay class , It contains a pair of Month and Day, Very useful for birthday . The YearMonth Class covers the use cases of credit card start date and expiration date, and scenarios where people don't specify a date .

Java SE 8 Medium JDBC These new types will be supported , But it won't change the public JDBC API. Existing generics setObject and getObject The method is enough .

These types can be mapped to vendor specific database types or ANSI SQL type .

12 summary

Java SE 8 stay java.time With a new date and time API, Provides developers with greatly improved security and functionality . new API Well modeled the field , And provides a large number of classes for modeling various developer use cases .

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[JavaEdge]所创,转载请带上原文链接,感谢
https://javamana.com/2021/02/20210223132350841x.html

  1. Java collection processing / null value processing / exception processing, use experience sharing!
  2. mysql Innodb_flush_log_at_trx_commit 和 sync_binlog
  3. mysql Innodb_ flush_ log_ at_ trx_ Commit and sync_ binlog
  4. 不能回滚的Redis事务还能用吗
  5. 不能回滚的Redis事务还能用吗
  6. Can redis transactions that cannot be rolled back be used
  7. 23种java设计模式
  8. Java、JavaScript、C、C++、PHP、Python都是用来开发什么?
  9. Docker overlay 清理空间
  10. 「Linux」- 安装 Opera 浏览器 @20210223
  11. java的byte和C#的byte的不同之处
  12. Can redis transactions that cannot be rolled back be used
  13. 23 Java design patterns
  14. What are Java, JavaScript, C, C + +, PHP and python used to develop?
  15. Docker overlay cleaning space
  16. "Linux" - install opera browser @ 20210223
  17. Differences between Java byte and C byte
  18. SAP UI5 JavaScript文件的lazy load - 懒加载
  19. Java 在Excel中添加筛选器并执行筛选
  20. LiteOS:盘点那些重要的数据结构
  21. Lazy load lazy load of SAP ui5 JavaScript files
  22. Add filter and execute filter in excel by Java
  23. Liteos: inventory those important data structures
  24. HDFS依然是存储的王者
  25. [MySQL]事务的MVCC原理与幻读
  26. 93.7%的程序员!竟然都不知道Redis为什么默认16个数据库?
  27. Java 集合处理/ 空值处理/ 异常处理,使用心得分享!
  28. Spring Authorization Server 全新授权服务器整合使用
  29. Spring Security 实战干货:OAuth2登录获取Token的核心逻辑
  30. Java中各种锁的原理解析
  31. java的byte和C#的byte的不同之处
  32. Java 在Excel中添加筛选器并执行筛选
  33. HDFS is still the king of storage
  34. Mvcc principle and unreal reading of [MySQL] transaction
  35. 93.7% of programmers! Why does redis default to 16 databases?
  36. Java collection processing / null value processing / exception processing, use experience sharing!
  37. Integrated use of new authorization server of spring authorization server
  38. Spring security real combat dry goods: the core logic of oauth2 login to obtain token
  39. Principle analysis of various locks in Java
  40. Differences between Java byte and C byte
  41. Add filter and execute filter in excel by Java
  42. Dialogue in spring
  43. 解决Docker MySQL无法被宿主机访问的问题
  44. Oracle OCP 19c 认证1Z0-083考试题库(第1题)
  45. Solve the problem that docker MySQL cannot be accessed by the host
  46. Oracle OCP 19C certification 1z0-083 examination question bank (question 1)
  47. 在 2021 年你需要掌握的 7 种关于 JavaScript 的数组方法
  48. Seven array methods for JavaScript you need to master in 2021
  49. 在 2021 年你需要掌握的 7 种关于 JavaScript 的数组方法
  50. Struts2 + Json _ 配置,异常解决及深入了解Struts2返回JSON数据的原理及具体应用范例
  51. Seven array methods for JavaScript you need to master in 2021
  52. Struts2 + Json _ Configuration, exception resolution and in-depth understanding of Struts2 return JSON data principle and specific application examples
  53. (三)MySQL锁机制 + 事务
  54. (3) MySQL lock mechanism + transaction
  55. 在 2021 年你需要掌握的 7 种关于 JavaScript 的数组方法
  56. Seven array methods for JavaScript you need to master in 2021
  57. 基于Kafka和Elasticsearch构建实时站内搜索功能的实践
  58. Practice of building real time search function in the website based on Kafka and elasticsearch
  59. Golang 实现 Redis(9): 使用GeoHash 搜索附近的人
  60. RxHttp - 轻量级、可扩展、易使用、完美兼容MVVM、MVC架构的网络封装类库