Starting with JDK8, Java provides new date-time handling methods to replace the old Date class. This chapter focuses on their usage and their interaction with older date classes.

Date and time

Java new date utility class in Java. Time package and subpackage, the main date class is LocalDateTime, LocalDate, LocalTime, these three API classes are very similar, the following is the common API and description.

Now () static method that gets the current date and time. Example: LocalDateTime. Now ()

Of () static method that generates LoalDateTime with the specified date and time. Example: localDatetime. of(2020, 2, 9, 8, 0, 0). If LocalDate is used, only year, month and day can be specified. If LocalTime is used, only the minute and second can be specified.

Plus () adds time to the current time and returns a new LocalDateTime without changing the original time. Generally, it is easier to use the following methods:

methods instructions note
plusYears(1) Add 1 year LocalTime Does not have this method
plusMonths(1) Add 1 month LocalTime Does not have this method
plusWeeks(1) Add 1 week LocalTime Does not have this method
plusDays(1) Add 1 day LocalTime Does not have this method
plusHours(1) Add 1 hour LocalDate does not have this method
plusMinutes(1) Add 1 minute LocalDate does not have this method
plusSeconds(1) Add 1 second LocalDate does not have this method

Minus () subtracts the time from the current time and returns the new LocalDateTime without changing the original time. Generally, it is easier to use the following methods:

methods instructions note
minusYears(1) Reduced by 1 year LocalTime Does not have this method
minusMonths(1) Reduce by 1 month LocalTime Does not have this method
minusWeeks(1) Reduced by 1 week LocalTime Does not have this method
minusDays(1) Reduced by 1 day LocalTime Does not have this method
minusHours(1) Reduce by 1 hour LocalDate does not have this method
minusMinutes(1) Reduce by 1 minute LocalDate does not have this method
minusSeconds(1) Reduced by 1 second LocalDate does not have this method

As you can see from the examples above, LocalDate does not handle time, LocalTime does not handle dates, and LocalDateTime is a collection of LocalDate and LocalTime.

  • Gets the number of milliseconds from 1970-01-01 00:00:00 to the current object:
LocalDateTime.now().toInstant(ZoneOffset.of("+ 8")).toEpochMilli();
Copy the code

If it is a LocalDate or LocaTime, convert it to a LocalDateTime object and obtain the number of milliseconds

  • Turn LocalDate LocalDateTime
// atTime() can set the time (hour, minute, second), or pass the LocalTime object
LocalDate.now().atTime(0.0.0);
// If you do not need to specify the time of the day, use this method to specify the time, minute and second is 0
LocalDate.now().atStartOfDay();
Copy the code
  • Turn a LocalTime LocalDateTime
LocalTime.now().atDate(LocalDate.now());
Copy the code

AtDate () passes in the LocalDate object

  • LocalDateTime Goes to LocalDate and LocalTime
// Get the date
LocalDate date = LocalDateTime.now().toLocalDate();
// Get time
LocalTime time = LocalDateTime.now().toLocalTime();
Copy the code
  • LocalDateTime converges with Date
/** * LocalDateTime to udate *@param datetime
 * @return* /
public static Date localDateTimeToUDate(LocalDateTime datetime) {

	ZoneId zone = ZoneId.systemDefault();
	Instant instant = datetime.atZone(zone).toInstant();
	Date udate = Date.from(instant);
	return udate;
}

/** * udate to LocalDateTime *@param date
 * @return* /
public static LocalDateTime uDateToLocalDateTime(Date date) {

	Instant instant = date.toInstant();
	ZoneId zone = ZoneId.systemDefault();
	LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
	return localDateTime;
}
Copy the code

The time zone

If the system has foreign users, you may need to perform this operation based on different regions and time zones. Java uses Green time (UTC) and we can use ZoneOffset to set the offset position.

// zoneoffset. of("+8")
LocalDateTime.now().toInstant(ZoneOffset.of("+ 8")).toEpochMilli();
Copy the code

formatting

In the old Date class, dates are formatted using SimpleDateFormat, which is not thread-safe. Use the DateTimeFormatter in the new date class

LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
log.info("- > {}", formatter.format(now));
Copy the code

DateTimeFormatter defines some preformatting methods. Here is the reference table:

You can also customize the format:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
/ / format
String str = formatter.format(LocalDateTime.now());
/ / to LocalDateTime
LocalDateTime datetime = LocalDateTime.parse("The 2021-01-01 08:00:00", formatter);
Copy the code

Here is the Pattern expression reference table:

The new time tool is more complex, but also more flexible. The new toolkit is recommended for future development.


All are “Siege Lion · Zheng” unless noted. Link to this article: engr-z.com/207.html