Java8 time processing class usage practice (LocalDate...)

Java8 time processing class usage practice (LocalDate...)

With it, who still uses Date? Calendar?

In fact, it can't be so absolute, after all, it hasn't reached that level yet. Java8 has added a new set of classes (LocalDate, LocalDateTime, LocalTime) for processing time. When I first started using it, I felt very laborious, not as easy to use as Calendar, but after I really used it, I thought it was quite easy to use. It is recommended that you use it more in the future. Stop talking nonsense, look at the code~

1. Interchange between Date and LocalDate

Date转LocalDate:

Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

LocalDate 转 Date:

LocalDateTime localDateTime = LocalDateTime.now();
Date date = Date.from(localDateTime.toInstant(ZoneOffset.UTC))

Obviously, Instant is used to convert the type between LocalDate and Date, and other methods can also be used to convert. LocalDate.of() and so on, it's a little more complicated!

2. Some time operations of LocalDate

copy code
1 DateTimeFormatter ymd = DateTimeFormatter.ofPattern("yyyy-MM-dd" );
 2  // Convert the string to LocalDate type 
3 LocalDate ld = LocalDate.parse("2015-11-23" , ymd);
 4 System.out. println("year month day: "+ld.getYear()+"-"+ld.getMonthValue()+"-"+ ld.getDayOfMonth());
 5 System.ouot.println("From January 1, 1970 The total number of days since the beginning of the day: "+ ld.toEpochDay());
 6 ld = LocalDate.of(2015,11,25 );
 7 System.out.println("New Year's Day: "+ld.getYear()+" -"+ld.getMonthValue()+"-"+ ld.getDayOfMonth());
 8  
9 ld = ld.plusDays(1 );
 10System.out.println("Add day, month and day: "+ld.getYear()+"-"+ld.getMonthValue()+"-"+ ld.getDayOfMonth());
 11  
12 ld = ld.minusDays( 2 );
 13 System.out.println("Subtract two days of year, month and day: "+ld.getYear()+"-"+ld.getMonthValue()+"-"+ ld.getDayOfMonth());
 14  
15 ld = ld.plusMonths(1 );
 16 System.out.println("Add month month day: "+ld.getYear()+"-"+ld.getMonthValue()+"-"+ ld.getDayOfMonth() );
 17  
18 ld = ld.minusMonths(1 );
 19 System.out.println("Subtract one month month day: "+ld.getYear()+"-"+ld.getMonthValue()+"-"+ ld.getDayOfMonth());
20  
21 ld.plusWeeks(1); // Add one week
22 ld.plusYears(1); // plus one year 
23 ld.minusWeeks(1); // minus one week 
24 ld.minusYears(1); // minus one year
copy code

It is so powerful that we don't have to manually calculate these things, saving trouble, effort, and flexibility.

3. Partial framework support

Because the project is Spring4+MyBatis3, I only tested the support of these two frameworks.

(1) Spring4 supports LocalDate. Do the following format conversion when spring mvc receives parameters:

1 @RequestMapping("/test")
2 public void method(HttpServletRequest request,HttpServletResponse response,
3 @DateTimeFormat(pattern="yyyy-MM-dd") LocalDate localDate){
4 //接收处理逻辑
5 }

It is also necessary to explain the received parameters of Spring MVC: if it is the incoming Date type, it also needs to be formatted with the annotation @DateTimeFormat, otherwise a 400 parameter error will be reported. If it is a bean object and contains a Date or LocalDate type field, you also need to add the annotation @DateTimeFormat.

 

(2)MyBatis3 对LocalDate的支持。现阶段还是不支持的,需要我们做些处理。

方案一、修改MyBatis包源码。不到迫不得已的情况下,是不会尝试的。

方案二、增加一个Handler处理类型转换。网上找到的处理方案,亲试,完全可以。

此处只介绍方案二,大牛可以去尝试下方案一。

第一步:创建转换器

copy code
 1 package com.hfms.mybatis.type;
 2  
 3 import java.sql.CallableStatement;
 4 import java.sql.PreparedStatement;
 5 import java.sql.ResultSet;
 6 import java.sql.SQLException;
 7 import java.sql.Timestamp;
 8 import java.time.LocalDateTime;
 9 
10 import org.apache.ibatis.type.BaseTypeHandler;
11 import org.apache.ibatis.type.JdbcType;
12 import org.apache.ibatis.type.MappedTypes;
13  /**
14   *类型转换器,以LocalDateTime为例,使用LocalDate需做相应修改
15   *
16   **/
17 @MappedTypes(LocalDateTime.class)
18 public class LocalDateTimeTypeHandler extends BaseTypeHandler<LocalDateTime> {
19  
20     @Override
21     public void setNonNullParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType) throws SQLException {
22         ps.setTimestamp(i, Timestamp.valueOf(parameter));
23     }
24  
25     @Override
26     public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
27         Timestamp date = rs.getTimestamp(columnName);
28         if (date == null) {
29             return null;
30         } else {
31             return date.toLocalDateTime();
32         }
33     }
34  
35     @Override
36     public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
37         Timestamp date = rs.getTimestamp(columnIndex);
38         if (date == null) {
39             return null;
40         } else {
41             return date.toLocalDateTime();
42         }
43     }
44  
45     @Override
46     public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
47         Timestamp date = cs.getTimestamp(columnIndex);
48         if (date == null) {
49             return null;
50         } else {
51             return date.toLocalDateTime();
52         }
53     }
54 }
copy code

第二步:在mybatis-config.xml中配置

1 <typeHandlers>
2     <package name="com.hfms.mybatis.type"/>
3 </typeHandlers>

第三步:创建对象的时候使用:

1 public class Test{
2   LocalDateTime localDateTime;   
3 }

这样在TestHandler.xml中就可以直接使用了。


Reprinted from: http://www.cnblogs.com/quanenmin/p/4993929.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325496662&siteId=291194637