This is the 15th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021.
Java 8 further enhances Date and Time handling with the release of a new date-time API (JSR 310).
There were a number of issues with the date-time API in older versions of Java, among them:
- Non-thread-safe − Java.util. Date is non-thread-safe, and all Date classes are mutable, which is one of the biggest problems with Java Date classes.
- Poor design – Java’s date/time classes are not consistently defined, with date classes in both java.util and java.sql packages, and classes for formatting and parsing in the java.text package. Date contains both Date and time, whereas java.sql.Date only contains dates, which makes it unreasonable to include in the java.sql package. The other two classes have the same name, which in itself is a very bad design.
- Date classes do not provide internationalization and there is no TimeZone support, so Java introduced java.util.Calendar and java.util.TimeZone classes, which suffer from all of the above problems.
In Java8, the new time and date API is located in the java.time package, which contains important classes. What do they represent?
Instant: indicates the timestamp
Duration
LocalDate: contains only the date, for example, 2021-10-20
LocalTime: contains only the time, for example, 231210
LocalDateTime: contains the date and time, for example, 2021-10-20 231421
-Penny: Period.
ZoneOffset: time ZoneOffset, for example, +8:00
ZonedDateTime: time with time zone
Clock: a Clock, such as the current time in New York
The new java.time package covers all operations that handle date, time, date/time, time zone, instants, during, and clock.
What is the difference between LocalTime and LocalDate?
LocalDate indicates the date, year, month and day, and LocalTime indicates the time, hour and second
Get the current time
In Java8, use the following method to obtain the current time:
LocalDate today = LocalDate.now();
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 ErrorOK!Copy the code
The time when the specified date is created
LocalDate date = LocalDate.of(2021.01.01); Copy ErrorOK!Copy the code
Check the leap year
To check whether the leap year is a leap year, use isLeapYear of LocalDate
LocalDate nowDate = LocalDate.now();
// Determine leap years
booleanleapYear = nowDate.isLeapYear(); Copy ErrorOK!Copy the code
Count the number of days and months between two dates
In Java 8, you can use the java.time.Period class to do calculations.
Period period = Period.between(LocalDate.of(2021.1.1),LocalDate.of(2021.5.5));
Copy the code