Processing method of date and time in Java 8

Java 8 has added localdate and Localtime interfaces. Why do you want a new set of APIs for processing date and time? Because the old Java util. Date is too difficult to use.

java. util. Date month starts from 0. January is 0 and December is 11. Pervert! java. time. If the month and week of localdate are changed to enum, it is impossible to make a mistake.

java. util. Neither date nor simpledateformatter is thread safe. Like the most basic string, localdate and Localtime are immutable types. They are thread safe and cannot be modified.

java. util. Date is a "universal interface", which contains date, time and milliseconds. If you only want to use Java util. Date stores date, or only time, so only you know which parts of the data are useful and which parts of the data are unavailable. In the new Java 8, date and time are clearly divided into localdate and Localtime. Localdate cannot contain time and Localtime cannot contain date. Of course, localdatetime can contain both date and time.

The reason why the new interface works better is that the operation of date and time is taken into account. It often pushes forward or backward for a few days. Use Java util. Date and calendar need to write a lot of code, and ordinary developers may not be able to write it correctly.

LocalDate

See how to use the new localdate:

LocalDate. parse("2014-02-29"); // Invalid date: datetimeparseexception: invalid date

Date conversion is often encountered, such as:

LocalTime

Localtime only contains time, which was previously used in Java util. How can date only represent time? The answer is to pretend to ignore the date.

Localtime contains milliseconds:

LocalTime Now = LocalTime. Now(); // 11:09:09.240

You may want to clear milliseconds:

LocalTime Now = LocalTime. Now(). withNano(0)); // 11:09:09

The construction time is also simple:

LocalTime zero = LocalTime. of(0,0); // 00:00:00 LocalTime mid = LocalTime. parse("12:00:00"); // 12:00:00

Time is also recognized according to ISO format, but the following three formats can be recognized:

•12:00 •12:01:02 •12:01:02.345

JDBC

The latest JDBC mapping will associate the date type of the database with the new type of Java 8:

sql -> Java --------------------------

date -> LocalDate time -> LocalTime timestamp -> LocalDateTime

Mapping to Java. Net will never occur again util. Date where some part of the date or time is 0.

The above is the processing method of date and time in Java 8 introduced by Xiaobian. I hope it will help you. If you have any questions, please leave me a message, and Xiaobian will reply to you in time. Thank you very much for your support for the programming tips website!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>