Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - How to happily handle dates and times in Java 8
How to happily handle dates and times in Java 8

To happily handle dates and times, it is enough that you have upgraded to java8, because Java 8 has new LocalDate and LocalTime interfaces for handling dates and times. ?

Let’s first look at how to use the new LocalDate: //? Get the current date:

LocalDate?today?=?LocalDate.now();?//?->? 2014-12-24

//?Get the date based on the year, month and day, December is 12:

LocalDate?crischristmas?=?LocalDate.of(2014,?12,? 25);?//?->?2014-12-25

//?According to the string:

LocalDate?endOfFeb?=?LocalDate.parse("2014- 02-28");?//?Verify strictly in accordance with ISO?yyyy-MM-dd. Even writing 02 as 2 will not work. Of course, there is an overloaded method that allows you to define the format yourself

LocalDate.parse("2014 -02-29");?//?The invalid date cannot be passed: DateTimeParseException:?Invalid?date

Date conversion is often encountered, such as: //?Get the first day of this month:

LocalDate?firstDayOfThisMonth?=?today.with(TemporalAdjusters.firstDayOfMonth());?//?2014-12-01

//?Get the 2nd day of this month:

LocalDate?secondDayOfThisMonth?=?today.withDayOfMonth(2);?//?2014-12-02

//?Take the last day of the month, no longer need to calculate 28, 29 , 30 or 31:

LocalDate?lastDayOfThisMonth?=?today.with(TemporalAdjusters.lastDayOfMonth());?//?2014-12-31

//?Remove Day:

LocalDate?firstDayOf2015?=?lastDayOfThisMonth.plusDays(1);?//?becomes 2015-01-01

//?Take the first day of January 2015 On a Monday, using Calendar for this calculation will cost a lot of brain cells:

LocalDate?firstMondayOf2015?=?LocalDate.parse("2015-01-01").with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY ));?//?2015-01-05

LocalTime

LocalTime only contains time. How could we use java.util.Date to express only time in the past? The answer is, pretend to ignore the date.

LocalTime contains milliseconds:

LocalTime?now?=?LocalTime.now();?//?11:09:09.240

You may want to clear Number of milliseconds: LocalTime?now?=?LocalTime.now().withNano(0));?//?11:09:09

Constructing time is also very simple: LocalTime?zero?=?LocalTime .of(0,?0,?0);?//?00:00:00

LocalTime?mid?=?LocalTime.parse("12:00:00");?// ?12:00:00

The time is also recognized in 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 database's date type with the new Java 8 type: SQL?->? Java

--------------------------

date?->?LocalDate

time?->?LocalTime

timestamp?->?LocalDateTime

never again maps to java.util.Date where some part of the date or time is 0 situation.