Java自用日期时间转换工具类
由于在工作用遇到数据库存储格式为 LocalDateTime 格式的日期时间,但前端传的为 String 类型的日期时间,需要转换类型,故自整理此工具类,后续有新功能再进行完善。
package com.domain.utils;
import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Date;
public abstract class DateTimeUtils {
private DateTimeUtils() { }
private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private static final DateTimeFormatter DATE_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
public static LocalDateTime strToLocalDateTime(String str) { try { return LocalDateTime.parse(str, DATE_TIME); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("日期时间转换工具异常"); } }
public static LocalDate strToLocalDate(String str) { try { return LocalDate.parse(str, DATE); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("日期时间转换工具异常"); } }
public static String localDateTimeToStr(LocalDateTime localDateTime) { try { return localDateTime.format(DATE_TIME); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("日期时间转换工具异常"); } }
public static String localDateToStr(LocalDate localDate) { try { return localDate.format(DATE); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("日期时间转换工具异常"); } }
public static Date localDateTimeToDate(LocalDateTime localDateTime) { try { return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("日期时间转换工具异常"); } }
public static Date localDateTimeToDate(LocalDateTime localDateTime, Integer hours) { try { return Date.from(localDateTime.toInstant(ZoneOffset.ofHours(hours))); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("日期时间转换工具异常"); } }
public static Date localDateToDate(LocalDate localDate) { try { return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("日期时间转换工具异常"); } }
public static Date localDateToDate(LocalDate localDate, Integer hours) { try { return Date.from(localDate.atStartOfDay().toInstant(ZoneOffset.ofHours(hours))); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("日期时间转换工具异常"); } } }
|