Java8 new features column: https://blog.csdn.net/caoyuan666/category_11801993.html?spm=1001.2014.3001.5482
Article directory
0 Preface
In order to solve the thread-unsafe problem of Date, Calendar and other time and date related classes before java8 (errors will be reported when using multi-threading to change them), java8 introduces a more convenient and complete java.time. The overall structure diagram is shown below.
1.LocalDate、LocalTime、LocalDateTime
According to requirements, the new java.time provides LocalDate, LocalTime, and LocalDateTime to represent date, time, and date+time respectively. how to use themsimilar, here only take LocalDateTime as an example
1.1 Creation method
There are generally two ways to create, get the current time through now(), and get the specified date and time through of()
- now() gets the current date-time from the system clock in the default timezone.
- now(Clock clock) Gets the current date-time from the specified clock.
- now(ZoneId zone) Gets the current date-time from the system clock in the specified time zone.
LocalDateTime now1 = LocalDateTime.now();
LocalDateTime now2 = LocalDateTime.now(ZoneId.of("Asia/Tokyo"));
System.out.println(now1);
System.out.println(now2);
2022-05-07T16:29:03.640
2022-05-07T17:29:03.640
- of(int year, int month, int dayOfMonth, int hour, int minute, int second)
of() has an overloaded static method, detailed development manual
LocalDateTime dt1 = LocalDateTime.of(2022, 2, 2, 2, 20, 20);
System.out.println(dt1);
// 2022-02-02T02:20:20
1.2 Common methods
The get method is used to get the response value
return type | method | describe |
---|---|---|
int | get(TemporalField field) | Get the specified field's value as int from this datetime |
int | getDayOfMonth() | Get the month field. |
DayOfWeek | getDayOfWeek() | Get the day of the week field, which is an enumeration DayOfWeek |
int | getDayOfYear() | Get the date field. |
int | getHour() | Get the time field. |
long | getLong(TemporalField field) | Gets the specified field's value as long from this datetime |
int | getMinute() | Get the hour field. |
Month | getMonth() | Use the Month enum to get the month field. |
int | getMonthValue() | Set the month field from 1 to 12. |
int | getNano() | Get the second field in nanoseconds. |
int | getSecond() | Get the second minute field. |
int | getYear() | Get the year field. |
comparison method
return type | method | describe |
---|---|---|
boolean | isAfter(ChronoLocalDateTime<?> other) | Checks if this datetime is after the specified date. |
boolean | isBefore(ChronoLocalDateTime<?> other) | Checks if this datetime is before the specified datetime. |
boolean | isEqual(ChronoLocalDateTime<?> other) | Checks if this datetime is equal to the specified datetime. |
Addition and subtraction method: used to process according to the response unit
- plusxxx(),如plusSeconds(long seconds)
- minusxxx(),如minusHours(long hours)
2. Formatting and parsing
DateTimeFormatter: Mainly used for parsing and formatting between datetime & String
LocalDateTime ldt = LocalDateTime.of(1997, 1, 1, 10, 10);
String s = ldt.toString();
System.out.println(s);
// 1.自定义格式化&解析
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yy:MM:dd===HH:mm:ss");
String format = ldt.format(dtf);
String format1 = dtf.format(ldt);
System.out.println(format);
System.out.println(format1);
TemporalAccessor parse = dtf.parse(format);
System.out.println(parse.getClass());
LocalDateTime parse1 = LocalDateTime.parse(format1, dtf);
System.out.println(parse);
System.out.println(parse1);
System.out.println("-----------------");
// 2.ISO_LOCAL_DATE标准格式化
DateTimeFormatter isoDateTime = DateTimeFormatter.ISO_LOCAL_DATE;
LocalDate ld = LocalDate.now();
String format2 = ld.format(isoDateTime);
System.out.println(format2);
System.out.println("-----------------");
// 3.时间格式化
LocalTime now = LocalTime.now();
DateTimeFormatter isoLocalTime = DateTimeFormatter.ISO_LOCAL_TIME;
System.out.println(now.format(isoLocalTime));
1997-01-01T10:10
97:01:01===10:10:00
97:01:01===10:10:00
class java.time.format.Parsed
{},ISO resolved to 2097-01-01T10:10
2097-01-01T10:10
-----------------
2022-05-07
-----------------
17:02:38.774
Process finished with exit code 0
3. Time zone
- ZoneId: time zone ID
- ZoneOfferset: time zone offset
LocalDateTime now1 = LocalDateTime.now();
LocalDateTime now2 = LocalDateTime.now(ZoneId.of("Australia/Sydney"));
System.out.println(now1);
System.out.println(now2);
System.out.println(ZoneOffset.UTC);
System.out.println(ZoneOffset.ofHours(8));
2022-05-07T19:01:35.412
2022-05-07T21:01:35.414
Z
+08:00
4. Timestamp
- Timestamp: the first year of Unix: January 1, 1970 00:00:00 to a certain time in milliseconds
- UTC time: the reference time of the time zone where the meridian is located, the default time zone obtained by the timestamp
- Convert with LocalDateTime, pay attention to the time zone, my country is East 8 District
Instant now = Instant.now();
long epochSecond = now.getEpochSecond();
Instant instant1 = Instant.ofEpochSecond(epochSecond);
System.out.println(now);
System.out.println(epochSecond);
System.out.println(instant1);
System.out.println("-------------");
// LocalDateTime & Instant 转换
LocalDateTime dateTime = LocalDateTime.ofInstant(now, ZoneId.of("Asia/Shanghai"));
LocalDateTime dateTime1 = LocalDateTime.ofInstant(now, ZoneId.systemDefault());
Instant instant = dateTime.toInstant(ZoneOffset.ofHours(8));
System.out.println(dateTime);
System.out.println(dateTime1);
System.out.println(instant);
2022-05-07T10:59:34.371Z
1651921174
2022-05-07T10:59:34Z
-------------
2022-05-07T18:59:34.371
2022-05-07T18:59:34.371
2022-05-07T10:59:34.371Z
Process finished with exit code 0
5. Interval
- Before time: Duration
- Between dates: Period
Get the interval between two points, which can be converted to the time unit that needs to be displayed:
- getXXX(): such as getSeconds()
- toXXX(): such as toMillis()
LocalDateTime start = LocalDateTime.now();
Thread.sleep(1000);
LocalDateTime end = LocalDateTime.now();
System.out.println(Duration.between(start, end).getSeconds());
System.out.println(Duration.between(start, end).toMillis());
1
1002
6. Time Regulator
Adjust dates with TemporalAdjust to find the next desired date
- TemporalAdjuster: Functional interface, as shown below, can be implemented by yourself
- TemporalAdjusters: A tool class that implements the TemporalAdjuster interface, providing common methods
@FunctionalInterface
public interface TemporalAdjuster {
Temporal adjustInto(Temporal temporal);
}
Example operation:
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
System.out.println(now.getDayOfWeek());
System.out.println(now.withDayOfMonth(1));
System.out.println(now.with(TemporalAdjusters.next(DayOfWeek.SUNDAY)));
System.out.println(now.with(TemporalAdjusters.firstDayOfNextMonth()));
// 找下一个工作日
LocalDateTime nextDate = now.with((obj) -> {
LocalDateTime date = (LocalDateTime) obj;
DayOfWeek dayOfWeek = date.getDayOfWeek();
if (dayOfWeek.equals(DayOfWeek.FRIDAY)) {
return date.plusDays(3);
} else if (dayOfWeek.equals(DayOfWeek.SATURDAY)) {
return date.plusDays(2);
} else {
return date.plusDays(1);
}
});
System.out.println(nextDate);
2022-05-07T19:31:33.665
SATURDAY
2022-05-01T19:31:33.665
2022-05-08T19:31:33.665
2022-06-01T19:31:33.665
2022-05-09T19:31:33.665