Java8日期工具类封装的实战记录
介绍
Java8中提供的日期时间API可以更方便地处理时间日期相关的操作,提高开发效率,提高代码可读性。但是,在实际项目中,我们需要将这些API封装成工具类,方便在整个项目中使用。本文将介绍如何封装Java8日期时间API,以及如何在项目中应用。
封装Java8日期工具类
创建工具类
创建一个名为DateUtil
的工具类,代码如下:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class DateUtil {
private static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
private static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
/**
* Date 转 LocalDate
*
* @param date
* @return
*/
public static LocalDate dateToLocalDate(Date date) {
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
}
/**
* Date 转 LocalDateTime
*
* @param date
* @return
*/
public static LocalDateTime dateToLocalDateTime(Date date) {
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
}
/**
* LocalDate 转 Date
*
* @param localDate
* @return
*/
public static Date localDateToDate(LocalDate localDate) {
return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
}
/**
* LocalDateTime 转 Date
*
* @param localDateTime
* @return
*/
public static Date localDateTimeToDate(LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
/**
* 格式化日期
*
* @param date
* @param format
* @return
*/
public static String formatDate(Date date, String format) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
return formatter.format(dateToLocalDateTime(date));
}
/**
* 获取当前日期
*
* @return
*/
public static LocalDate getCurrentLocalDate() {
return LocalDate.now();
}
/**
* 获取当前时间
*
* @return
*/
public static LocalDateTime getCurrentLocalDateTime() {
return LocalDateTime.now();
}
/**
* 获取当前日期时间字符串
*
* @return
*/
public static String getCurrentDateTimeString() {
return formatLocalDateTimeToString(getCurrentLocalDateTime(), DEFAULT_DATE_TIME_FORMAT);
}
/**
* LocalDateTime格式化为字符串
*
* @param localDateTime
* @param format
* @return
*/
public static String formatLocalDateTimeToString(LocalDateTime localDateTime, String format) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
return formatter.format(localDateTime);
}
}
测试工具类
为了验证工具类的正确性,我们可以编写以下两个测试用例:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
public class DateUtilTest {
@Test
public void testDateToLocalDate() {
Date date = new Date();
LocalDate localDate = DateUtil.dateToLocalDate(date);
assertEquals(localDate.getYear(), date.getYear() + 1900);
assertEquals(localDate.getMonthValue(), date.getMonth() + 1);
assertEquals(localDate.getDayOfMonth(), date.getDate());
}
@Test
public void testDateToLocalDateTime() {
Date date = new Date();
LocalDateTime localDateTime = DateUtil.dateToLocalDateTime(date);
assertEquals(localDateTime.getYear(), date.getYear() + 1900);
assertEquals(localDateTime.getMonthValue(), date.getMonth() + 1);
assertEquals(localDateTime.getDayOfMonth(), date.getDate());
assertEquals(localDateTime.getHour(), date.getHours());
assertEquals(localDateTime.getMinute(), date.getMinutes());
assertEquals(localDateTime.getSecond(), date.getSeconds());
}
}
工具类应用实例
示例一
我们将使用Java8日期工具类在Spring MVC项目中实现一个日期参数自动绑定的操作。在Spring MVC中,我们可以通过注解@InitBinder
来实现这个自动绑定。
在Controller中加入以下代码:
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.text.SimpleDateFormat;
import java.util.Date;
@Controller
public class HomeController {
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String test(Date date) {
System.out.println(date);
return "success";
}
@InitBinder
protected void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
}
我们会发现,在使用Java8日期类作为参数时,会报如下错误:
Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'
为了解决这个问题,我们需要写一个自定义的日期类型转换器,而这个日期类型转换器会使用我们封装好的Java8日期工具类。修改HomeController
:
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
@Controller
public class HomeController {
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String test(Date date) {
System.out.println(date);
return "success";
}
@InitBinder
protected void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService();
DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
registrar.setDateFormatter(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
registrar.setDateTimeFormatter(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
registrar.registerFormatters(conversionService);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
binder.registerCustomEditor(LocalDate.class, new LocalDatePropertyEditor(conversionService));
binder.registerCustomEditor(LocalDateTime.class, new LocalDateTimePropertyEditor(conversionService));
}
}
示例二
我们在Spring Boot项目中使用Hibernate来操作数据库,使用Java8日期工具类对Hibernate中的日期时间类型进行自动映射。
我们需要在src/main/resources/application.properties
中添加以下配置:
# MySQL
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
# Hibernate
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jackson.serialization.indent_output=true
# Use Java8 Clock specification as opposed to System.currentTimeMillis().
spring.data.jpa.convert.threeten=true
其中,spring.data.jpa.convert.threeten
属性设为true表示采用Java8日期类来进行时间戳的转换。
我们需要在实体类中使用Java8日期类进行日期时间类型的定义,例如:
import javax.persistence.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String username;
@Column(nullable = false)
private String password;
@Column(name = "create_date")
private LocalDate createDate;
@Column(name = "create_time")
private LocalDateTime createTime;
// 省略getter和setter方法
}
我们的UserRepository
接口可以这样写:
import org.springframework.data.repository.CrudRepository;
public interface UserRepository extends CrudRepository<User, Long> {
}
并且我们可以直接在Controller中使用UserRepository
来进行数据库操作:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
@Controller
@RequestMapping(value = "/user")
public class UserController {
@Autowired
private UserRepository userRepository;
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<String> addUser(@RequestParam("username") String username,
@RequestParam("password") String password,
@RequestParam("createDate") LocalDate createDate,
@RequestParam("createTime") LocalDateTime createTime) {
User user = new User();
user.setUsername(username);
user.setPassword(password);
user.setCreateDate(createDate);
user.setCreateTime(createTime);
userRepository.save(user);
return new ResponseEntity<>("OK", HttpStatus.OK);
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public List<User> listUser() {
return (List<User>) userRepository.findAll();
}
}
总结
本文介绍了如何封装Java8日期工具类,以及如何在Spring MVC和Spring Boot项目中应用Java8日期类。Java8日期类的使用可以有效地提高代码可读性和开发效率。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:java8日期工具类封装的实战记录 - Python技术站