A brief introduction to the Java 8 date api

preface

  • Before Java 8, we had many problems dealing with dates, such as cumbersome date conversion, difficult calculation, thread safety and so on. In order to solve these pain points, the java.time package is introduced into java8, and the new date processing method fundamentally solves these pain points.

Common API descriptions

  • LocalDateTime refers to the date and time without time zone, which is generally expressed as: year, day, hour, minute and second, immutable and thread safe.

  • LocalDate refers to the date and time without time zone. Generally, it refers to month, year and day. It is immutable and thread safe.

  • LocalTime refers to the date and time without time zone. It generally means: hour, minute and second, immutable and thread safe.

  • ZoneId the Id of the time zone

  • ZonedDateTime has the date and time of the time zone. It stores all date and time fields with the precision of nanoseconds and the time zone is the area offset. It is used to deal with fuzzy local date and time.

  • Instant models a single instantaneous point on the timeline and represents a point (instantaneous) on the timeline. It is mainly used for mutual conversion between Date and our new Date api

  • Duration refers to a period of time, which can be used to calculate the interval between two times (hours, minutes, seconds, etc.)

  • Period refers to a period of time, which can be used to calculate the interval between two dates (month, year, day, etc.)

    We mainly focus on three basic objects: LocalDate, LocalTime and LocalDateTime

Use example

  • Get the current time and use now() to create the object
LocalDateTime localDateTime = LocalDateTime.now();
LocalDate localDate = LocalDate.now();
LocalTime localTime = LocalTime.now();
ZonedDateTime zonedDateTime = ZonedDateTime.now();
Instant instant = Instant.now();
Year year = Year.now();
YearMonth yearMonth = YearMonth.now();
MonthDay monthDay = MonthDay.now();
System.out.println("localDateTime:" + localDateTime);
System.out.println("localDate:" + localDate);
System.out.println("localTime:" + localTime);
System.out.println("zonedDateTime:" + zonedDateTime);
System.out.println("instant:" + instant);
System.out.println("year:" + year);
System.out.println("yearMonth:" + yearMonth);
System.out.println("monthDay:" + monthDay);

---console output ---
localDateTime:2021-09-21T20:49:56.544
localDate:2021-09-21
localTime:20:49:56.544
zonedDateTime:2021-09-21T20:49:56.544+08:00[Asia/Shanghai]
instant:2021-09-21T12:49:56.545Z
year:2021
yearMonth:2021-09
monthDay:--09-21
  • Use of() to specify the creation time and date
LocalDateTime localDateTime = LocalDateTime.of(2021, 9, 21, 6, 30, 10);
LocalDate localDate = LocalDate.of(2021, 9, 21);
LocalTime localTime = LocalTime.of(6, 30, 10);
System.out.println("localDateTime:" + localDateTime);
System.out.println("localDate:" + localDate);
System.out.println("localTime:" + localTime);
//LocalDateTime can be created by passing in localDate and localTime
LocalDateTime localDateTime2 = LocalDateTime.of(localDate, localTime);
System.out.println("localDateTime2:" + localDateTime2);

---console output ---
localDateTime:2021-09-21T06:30:10
localDate:2021-09-21
localTime:06:30:10
localDateTime2:2021-09-21T06:30:10
  • time zone
    We can obtain a Set set through the methods in the provided ZoneId class, which encapsulates 600 time zones. You can output it to the console for viewing
Set<String> setZondId = ZoneId.getAvailableZoneIds();
setZondId.stream().forEach(System.out::println);

It also provides a way to obtain the default time zone of the current system

ZoneId zoneId = ZoneId.systemDefault();
//Console output: Asia/Shanghai
System.out.println(zoneId);

We can view the time in different time zones by adding a time zone to LocalDateTime. For example, we want to get the time in Shanghai and Tokyo

LocalDateTime now = LocalDateTime.now();
// Add a time zone using atZone
ZonedDateTime zonedDateTime = now.atZone(ZoneId.of("Asia/Shanghai"));
// The withzonesameeinstant() method of ZonedDateTime can change the time zone
ZonedDateTime zonedDateTime2 = zonedDateTime.withZoneSameInstant(ZoneId.of("Asia/Tokyo"));

System.out.println("Asia/Shanghai:" + zonedDateTime);
System.out.println("Asia/Tokyo:" + zonedDateTime2);

---console output ---
Asia/Shanghai:2021-09-21T21:18:13.499+08:00[Asia/Shanghai]
Asia/Tokyo:2021-09-21T22:18:13.499+09:00[Asia/Tokyo]

We can see that Tokyo is one hour more than Shanghai

  • Addition and subtraction of dates
    We can use plus() to add the date and minus() to reduce the date. The following is only an example of some methods. Please test others yourself
LocalDateTime now = LocalDateTime.now();
System.out.println("now:" + now);
LocalDateTime plusYears = now.plusYears(1);
LocalDateTime minusYears = now.minusYears(1);
System.out.println("plusYears:" + plusYears);
System.out.println("minusYears:" + minusYears);
LocalDateTime plusDays = now.plusDays(10);
LocalDateTime minusDays = now.minusDays(10);
System.out.println("plusDays:" + plusDays);
System.out.println("minusDays:" + minusDays);

---console output ---
now:2021-09-21T21:31:33.295
plusYears:2022-09-21T21:31:33.295
minusYears:2020-09-21T21:31:33.295
plusDays:2021-10-01T21:31:33.295
minusDays:2021-09-11T21:31:33.295

Here, we can pass in a negative number in the plus() method. The effect is to reduce the date, and the negative number passed in the minus() method is to add the date. The bottom layer of the two methods actually calls the same method.
We can also use another method for adding and subtracting dates, that is, plus (long amount to add, temporary unit)

LocalDateTime now = LocalDateTime.now();
System.out.println("now:" + now);
LocalDateTime nextYear = now.plus(1, ChronoUnit.YEARS);
LocalDateTime nextMonth = now.plus(1, ChronoUnit.MONTHS);
LocalDateTime nextDay = now.plus(1, ChronoUnit.DAYS);
System.out.println("nextYear:" + nextYear);
System.out.println("nextMonth:" + nextMonth);
System.out.println("nextDay:" + nextDay);

---console output ---
now:2021-09-21T21:43:19.384
nextYear:2022-09-21T21:43:19.384
nextMonth:2021-10-21T21:43:19.384
nextDay:2021-09-22T21:43:19.384
  • The with() method modifies the date directly
    If you do not need to add or subtract a date but want to modify it directly, you can use the with method
LocalDateTime now = LocalDateTime.now();
System.out.println("now:" + now);
LocalDateTime withYear = now.withYear(2030);
System.out.println("withYear:" + withYear);
LocalDateTime withMonth = now.withMonth(6);
System.out.println("withMonth:" + withMonth);

---console output ---
now:2021-09-21T21:48:55.118
withYear:2030-09-21T21:48:55.118
withMonth:2021-06-21T21:48:55.118

  • Gets the year, day, hour, minute and second of the date
LocalDateTime now = LocalDateTime.now();
int year = now.getYear();
int monthValue = now.getMonthValue();
int dayOfMonth = now.getDayOfMonth();
int hour = now.getHour();
int minute = now.getMinute();
int second = now.getSecond();
System.out.println("year:" + year + "__month:" + monthValue + "__day" + dayOfMonth + "__hour:" + hour
+ "__minute:" + minute + "__second:" + second);


---console output ---
year:2021__month:9__day21__hour:21__minute:58__second:6
  • Comparison before and after date
LocalDateTime date1 = LocalDateTime.of(2021, 9, 21, 10, 30, 30);
LocalDateTime date2 = LocalDateTime.of(2030, 10, 28, 10, 30, 30);
System.out.println("date1 Is it better than date2 Date small:" + date1.isBefore(date2));
System.out.println("date1 Is it better than date2 Date:" + date1.isAfter(date2));

---console output ---
date1 Is it better than date2 Date small: true
date1 Is it better than date2 Date: false
  • Interval calculation of dates
    The first is to calculate the time period between two dates
LocalDateTime date1 = LocalDateTime.of(2021, 9, 21, 10, 30, 30);
LocalDateTime date2 = LocalDateTime.of(2025, 11, 25, 11, 30, 30);
//Note that only hours, minutes and seconds are compared here, and the year, month and day are not considered
Duration duration = Duration.between(date1.toLocalTime(), date2.toLocalTime());
System.out.println("date1 and date2 Date interval" + duration.toHours() + "hour" + duration.toMinutes() + "minute"
		+ duration.toMillis() / 1000 + "second");
//Note that only year, month and day are compared here, and hour, minute and second are not considered
Period period = Period.between(date1.toLocalDate(), date2.toLocalDate());
System.out.println("date1 and date2 Date interval" + period.getYears() + "year" + period.getMonths() + "month"
		+ period.getDays() + "day");

---console output ---
date1 and date2 Date interval 1 hour 60 minutes 3600 seconds
date1 and date2 Date interval 4 years, February 4 days

Extension: since Period and Duration represent a time interval, we can directly add this date interval to a date

LocalDateTime now = LocalDateTime.now();
System.out.println("now:" + now);
//Here, the time interval is one year, one month and one day
Period period = Period.of(1, 1, 1);
LocalDateTime plusDate = now.plus(period);
System.out.println("plusDate:" + plusDate);

---console output ---
now:2021-09-21T22:24:05.166
plusDate:2022-10-22T22:24:05.166

The next step is to directly calculate the specific units (year, month, day, hour, minute and second) of successive date intervals

LocalDate date = LocalDate.of(2021, 9, 20);
LocalDate date2 = LocalDate.of(2022, 10, 21);
System.out.println("Interval year:" + ChronoUnit.YEARS.between(date, date2));
System.out.println("Interval months:" + ChronoUnit.MONTHS.between(date, date2));
System.out.println("Interval days:" + ChronoUnit.DAYS.between(date, date2));

---console output ---
Interval year: 1
 Interval months: 13
 Interval days: 396
  • Get some specific dates through some methods in TemporalAdjusters
LocalDateTime date = LocalDateTime.of(2021, 9, 20, 10, 30, 30);
//Gets the first day of the month for that date
LocalDateTime with = date.with(TemporalAdjusters.firstDayOfMonth());
//Gets the last day of the month for the date
LocalDateTime with2 = date.with(TemporalAdjusters.lastDayOfMonth());
//Get last Saturday based on this date
LocalDateTime with3 = date.with(TemporalAdjusters.previous(DayOfWeek.SATURDAY));
//Get the next Saturday based on this date
LocalDateTime with4 = date.with(TemporalAdjusters.next(DayOfWeek.SATURDAY));
  • Formatting of dates
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// LocalDateTime to string
LocalDateTime date = LocalDateTime.now();
String format = date.format(dateTimeFormatter);
System.out.println(format);
// String conversion LocalDateTime
String formatDate = "2021-09-21 22:46:26";
LocalDateTime parse = LocalDateTime.parse(formatDate, dateTimeFormatter);
System.out.println(parse);
  • Conversion between java.util.date and the new date api
//java.util.date conversion new date api
Date now = new Date();
LocalDateTime localDateTime = now.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
LocalDate localDate = now.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalTime localTime = now.toInstant().atZone(ZoneId.systemDefault()).toLocalTime();

// localDateTime conversion java.util.date
Date date1 = Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant());
// localDate to java.util.date
Date date2 = Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant());
// Note that when converting java.util.date from localTime, you must specify the year, month and day
Date date3 = Date.from(LocalTime.now().atDate(LocalDate.now()).atZone(ZoneId.systemDefault()).toInstant());

last

Used to the old date api, you may not be used to it when you first contact it, but practice makes perfect. come on. To better myself

Keywords: Java

Added by ernielou on Tue, 21 Sep 2021 22:02:17 +0300