package com.ms.common.util; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.Date; import java.util.Locale; /** * @author liu pei * @version 1.0.0 * @ClassName DateUtils.java * @Description * @createTime 2022年12月03日 10:30:00 */ public class DateUtils { /** * Date 转 LocalDateTime * @param date * @return */ public static LocalDateTime dateToLocalDate(Date date){ return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(); } /** * String 转 LocalDateTime * @param date * @return */ public static LocalDateTime strToLocalDate(String date){ DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime localDateTime = LocalDateTime.parse(date, df); return localDateTime; } /** * LocalDateTime 转 String * @param localDateTime * @return */ public static String localDateToStr(LocalDateTime localDateTime){ DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String format = df.format(localDateTime); return format; } /** * long 转 date * @param date * @return */ public static Date longToDate(Long date){ return new Date(date); } /** * 时间加分钟 * @param now * @param addDate * @return */ public static Date dateAdd(Date now, long addDate){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA); Date afterDate = new Date(now.getTime() + addDate); return afterDate; } /** * 天转分钟 * @param date * @return */ public static Long dateToTime(String date){ Long value = Long.valueOf(date) * 60 * 24; return value; } /** * date转long * @param date * @return */ public static long dateToLong(Date date){ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA); return date.getTime(); } /** * 字符串转日期 * @param str * @return */ public static Date strToDate(String str){ DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA); try { Date date = df.parse(str); return date; } catch (ParseException pe) { System.out.println(pe.getMessage()); } return null; } /** * 日期转字符串 * @param date * @return */ public static String dateToStr(Date date){ DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA); String sDate = df.format(date); return sDate; } /** * 添加小时 * @param day * @param hour * @return */ public static String addDateHour(String day, int hour){ SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = null; try { date = format.parse(day); } catch (Exception ex) { ex.printStackTrace(); } if (date == null) return ""; Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.HOUR, hour);// 24小时制 date = cal.getTime(); cal = null; return format.format(date); } }