The new Java8 features have been updated at a considerable length, and today we will focus on DateTime processing in the date and time library. Also, if you’re still using traditional Date, Calendar, and SimpleDateFormat apis to handle date-related operations in your projects, this is a great article to read. Refresh your knowledge base!

background

The java.util.Date and java.util.Calendar classes are not easy to use, do not support time zones, and are not thread-safe. The DateFormat class for formatting dates is also non-thread-safe.

Java8 introduces a new set of apis that provide better support for handling dates and times, clearly defining concepts such as Instant, duration, date, and time. Time zone and Period.

At the same time, it draws on some advantages of the Joda library, such as the time and date understanding of human and machine separated.

Introduction to the

The new date and time API core is in java.time. There are also related apis in java.time. Chrono, java.time.format, java.time.temporal and java.time.zone, but they are used less frequently.

Java8 commonly used date and time classes include LocalDate, LocalTime, Instant, Duration, Period, LocalDateTime, and ZonedDateTime.

  • LocalDate: indicates the date without the time, such as 2019-10-14. Can be used to store birthdays, anniversaries, start dates, etc.
  • LocalTime: In contrast to LocalDate, it is a time without a date.
  • LocalDateTime: contains the date and time, without offset information (time zone).
  • ZonedDateTime: The full datetime with the time zone, offset in UTC/ Greenwich Mean Time.
  • Instant: timestamp, similar to System.currentTimemillis ().
  • Duration: indicates a time period.
  • Period: used to indicate a Period of time measured in years, months and days.

In addition, there is a new DateTimeFormatter class for date resolution.

The best way to learn is to do it, and now we’re going to illustrate each point in the form of an example.

LocalDate- How do I get the date

The LocalDate class contains only the date, not the time. You only need to represent the date and not the time to use it.

LocalDate today = localdate.now (); System.out.println(today); int year = today.getYear(); int month = today.getMonthValue(); int day = today.getDayOfMonth(); System.out.printf("Year : %d Month : %d day : %d \t %n", year, month, day);Copy the code

In addition, you can use LocalDate to obtain the day of the month, week, day of the month, and leap year. See if the following code is very convenient.

LocalDate today = LocalDate.now();
// 月份中的第几天
int dayOfMonth = today.getDayOfMonth();
// 一周的第几天
DayOfWeek dayOfWeek = today.getDayOfWeek();
// 月份的天数
int length = today.lengthOfMonth();
// 是否为闰年
boolean leapYear = today.isLeapYear();Copy the code

The LocalDate object is retrieved from now above, or you can create any date using the static method of() or parse. You don’t have to have years starting from 1900, months starting from zero, etc.

LocalDate oneDay. = LocalDate of,10,1 (2019); System.out.println(oneDay); LocalDate parseDay = LocalDate.parse("2019-10-01"); System.out.println(parseDay);Copy the code

Print result: 2019-10-01.

LocalDate overrides the equals method, making it easy to compare dates.

LocalDate oneDay = localdate.of (2019, 10, 1); System.out.println(oneDay); LocalDate anyDay = localdate.of (2019, 10, 1); System.out.println(oneDay.equals(anyDay));Copy the code

A MonthDay or YearMonth class can also be extended for dates, which, as the name suggests, contain only months or months. The same applies to equals for comparison.

Also use before and after to compare the time before and after two dates.

boolean notBefore = LocalDate.parse("2019-10-01").isBefore(LocalDate.parse("2019-10-02"));
boolean isAfter = LocalDate.parse("2019-10-01").isAfter(LocalDate.parse("2019-10-02"));Copy the code

It also becomes convenient to add and subtract from a date the day after or the month before.

LocalDate tomorrowDay = LocalDate.now().plusDays(1);
LocalDate nextMonth =  LocalDate.now().plusMonths(1);Copy the code

In addition, we often need to obtain the start time of a day and the first day of the month.

LocalDate.now().atStartOfDay();
LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());Copy the code

LocalTime- How do I get the time

LocalTime is similar to LocalDate except that LocalDate does not contain a specific time, whereas LocalTime contains a specific time. You can also use the now or of methods to get objects.

LocalTime localTime = LocalTime.now(); LocalTime oneTime = LocalTime) of (10,10,10);Copy the code

LocalDate also has methods to parse, isBefore, get time units, etc., so I won’t go into details here.

Note that LocalTime gets the time in the format 11:41:58.904. So HH:mm:ss. NNN, where NNN is nanosecond.

There is also a constant “23:59:59.99” that we often define when querying the date range in the field.

// 23:59:59.999999999 LocalTime maxTime = localtime. MAX; // 00:00 LocalTime minTime = LocalTime.MIN;Copy the code

LocalDateTime- a combination of date and time

LocalDateTime indicates a combination of date and time. It can be created directly with the of() method, or it can be merged into a LocalDateTime by calling the atTime() method of LocalDate or the atDate() method of LocalTime.

Example of creation time:

LocalDateTime now = LocalDateTime.now(); LocalDateTime oneTime = LocalDateTime. Of,10,14,10,12,12 (2019); Localtime.now ().atdate (localdate.now ());Copy the code

LocalDateTime and LocalDate and LocalTime can be converted to each other. Other date addition and subtraction operations are similar to those above.

Instant- Gets the timestamp

Instant is used for a timestamp, similar to System.CurrentTimemillis (), but Instant is accurate to nano-second.

Instant can be created using the ofEpochSecond method in addition to the now() method.

Instant now = Instant.now();

Instant.ofEpochSecond(365 * 24 * 60, 100);Copy the code

The first parameter of ofEpochSecond indicates the second and the second parameter indicates the nanosecond. Overall: point in time of 100 nanoseconds 365 days after 1970-01-01 00:00:00.

Duration- Obtains the time range

The internal implementation of Duration is similar to Instant, but Duration represents a time period and is created using the Between method.

LocalDateTime from = LocalDateTime.now(); LocalDateTime to = LocalDateTime.now().plusDays(1); Duration duration = Duration.between(from, to); Long days = duration.todays (); // long hours = duration.tohours (); // long minutes = duration.tominutes (); // long seconds = duration.getseconds (); // long milliSeconds = duration.tomillis (); // long nanoSeconds = duration.tonanos ();Copy the code

A Duration object can also be created using the of() method, which takes the length of a time period and the unit of time.

Duration duration1 = Duration. Of (7, ChronoUnit.DAYS); Duration duration2 = Duration. Of (60, chronounit. SECONDS);Copy the code

Period- Gets the date segment

“Period” is similar to “Duration” in that it takes a Period of time in years, months and days. It can also be created using the “of” or “between” methods, where “between” takes LocalDate.

Period period = Period.of(1, 10, 25);

Period period1 = Period.between(LocalDate.now(), LocalDate.now().plusYears(1));Copy the code

ZonedDateTime- Create time zone time

ZonedDateTime class for handling dates and times with time zones. ZoneId indicates different time zones. There are about 40 different time zones.

Get a collection of all time zones:

Set allZoneIds = ZoneId.getAvailableZoneIds();Copy the code

Create time zone:

ZoneId zoneId = ZoneId.of("Asia/Shanghai");Copy the code

Convert LocalDateTime to a specific time zone:

ZonedDateTime zonedDateTime = ZonedDateTime.of(LocalDateTime.now(), zoneId);
Copy the code

Another class used with time zones is the OffsetDateTime class. OffsetDateTime is invariant and represents date-time offset. It stores all date and time fields, accurate to nanosecond, calculated from UTC/Greenwich offset.

Time and date formatting

The formatting of dates in Java8 is very simple. First of all, most of the above classes provide a parse method that directly parses the string to get the corresponding object.

The date and time can be formatted using the format method of LocalDateTime.

LocalDateTime dateTime = LocalDateTime.now();
String str = dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
System.out.println(str);
str = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
System.out.println(str);Copy the code

Can use DateTimeFormatter preset format, but can be by DateTimeFormatter. OfPattern method to specify the format.

Critical Point Review

The time and date apis in Java8 have the following key points:

  • Javax.time. ZoneId is provided to handle time zones.
  • LocalDate and LocalTime classes are provided.
  • All classes in the Time and Date API are thread-safe.
  • The basic concepts of time and date are clearly defined.
  • Core API: Instant, LocalDate, LocalTime, LocalDateTime, ZonedDateTime.
  • The DateTimeFormatter class is used to format and parse dates in Java.

So that’s it for the date and time feature in Java8. It’s a lot easier to use.

Java8 DateTime API and Examples


Program new horizon