这个 DateUtil.java 类,整理的是 Java 中常用的一些日期转换方法,我们在项目开发中经常会用到。本工具类目前是基于 jdk1.8 版本编写,后续会一直不断地迭代更新。
package com.general.utils;
import ccdmsp.premier.cloud.constant.AppConstants;
import ccdmsp.premier.cloud.enums.ResultCode;
import ccdmsp.premier.cloud.exception.ApplicationException;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* @author 易網°情深″
* @discription 日期操作工具类
* @create: 2020/03/22 17:55
*/
public final class DateUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(DateUtil.class);
public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static final String DATE_FORMAT_YYYYMMDD = "yyyy-MM-dd";
public static final String DATE_FORMAT_YYYYMMDD1 = "yyyy/MM/dd";
public static final String DATE_FORMAT_YYYYMM = "yyyy-MM";
public static final String DATE_FORMAT_YYYYMMDDHHMMSS = "yyyyMMddHHmmsssss";
private static final Integer MAX_MONTH = 12;
private DateUtil() {
throw new UnsupportedOperationException("Util class");
}
/**
* 获取当前时间
*
* @return
*/
public static Date getNowDate() {
Calendar calendar = Calendar.getInstance();
return calendar.getTime();
}
/**
* 获取指定日期月份的最后一天
*
* @param date
* @return
*/
public static Date getEndDateByMonth(Date date) {
Date firstDate = null;
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
firstDate = cal.getTime();
return firstDate;
}
/**
* 获取日期的月份
*
* @param date
* @return
*/
public static int getMonthByDate(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal.get(Calendar.MONTH) + 1;
}
/**
* 格式化时间为年月日
*
* @param date
* @return
*/
public static String toYMDString(Date date) {
if (null != date) {
return new SimpleDateFormat(DATE_FORMAT_YYYYMMDD).format(date);
} else {
return null;
}
}
/**
* 格式化时间为年月日时分秒
*
* @param date
* @return
*/
public static String toYMDHSString(Date date) {
if (null != date) {
return new SimpleDateFormat(DEFAULT_DATE_FORMAT).format(date);
} else {
return null;
}
}
/**
* 获取月份集合
*
* @return
*/
public static List<Integer> getMonthList() {
List<Integer> monthList = new ArrayList<>();
for (int i = 1; i <= MAX_MONTH; i++) {
monthList.add(i);
}
return monthList;
}
/**
* 格式化日期为 Date 类型默认年月日时分秒
*
* @param dateStr
* @return
*/
public static Date parseDateYMD(String dateStr) {
return parse(dateStr, DATE_FORMAT_YYYYMMDD);
}
public static Date parseDateYMD1(String dateStr) {
return parse(dateStr, DATE_FORMAT_YYYYMMDD1);
}
public static Date parseDateYM(String dateStr) {
return parse(dateStr, DATE_FORMAT_YYYYMM);
}
public static String toYMDHMSSString() {
return new SimpleDateFormat(DATE_FORMAT_YYYYMMDDHHMMSS).format(getNowDate());
}
/**
* 格式化日期为 Date 类型默认年月日
*
* @param dateStr
* @return
*/
public static Date parseDate(String dateStr) {
return parse(dateStr, DEFAULT_DATE_FORMAT);
}
private static Date parse(String yearMonth, String dateFormat) {
Date date = null;
try {
date = new SimpleDateFormat(dateFormat).parse(yearMonth);
} catch (Exception pe) {
LOGGER.error("Date call error", pe);
}
return date;
}
/**
* 日期增加月
*
* @param date
* @param iMonth
* @return
*/
public static Date addMonth(Date date, int iMonth) {
return addDate(date, Calendar.MONTH, iMonth);
}
/**
* 日期增加天数
*/
public static Date addDay(Date date, int iDate) {
return addDate(date, Calendar.DAY_OF_MONTH, iDate);
}
private static Date addDate(Date date, int iArg0, int iDate) {
Calendar canlendar = Calendar.getInstance();
canlendar.setTime(date);
canlendar.add(iArg0, iDate);
return canlendar.getTime();
}
public static Date addYear(Date date, int iYear) {
return addDate(date, Calendar.YEAR, iYear);
}
/**
* 日期增加秒
*/
public static Date addSecond(Date date, int iDate) {
return addDate(date, Calendar.SECOND, iDate);
}
/**
* 日期增加分钟
*/
public static Date addMinute(Date date, int iDate) {
return addDate(date, Calendar.MINUTE, iDate);
}
/**
* 根据日期获取所属季度
*
* @param date
* @return
*/
public static int getQuarter(Date date) {
int season = -1;
Calendar c = toCalendar(date);
if (null != c) {
//取值月份值(注:该值非真正的月份只是在 Calendar 中对应的月份真正值)
int myMonth = c.get(Calendar.MONTH);
switch (myMonth) {
case Calendar.JANUARY:
case Calendar.FEBRUARY:
case Calendar.MARCH:
season = 1;
break;
case Calendar.APRIL:
case Calendar.MAY:
case Calendar.JUNE:
season = 2;
break;
case Calendar.JULY:
case Calendar.AUGUST:
case Calendar.SEPTEMBER:
season = 3;
break;
case Calendar.OCTOBER:
case Calendar.NOVEMBER:
case Calendar.DECEMBER:
season = 4;
break;
default:
break;
}
}
return season;
}
private static Calendar toCalendar(Date date) {
Calendar c = null;
if (null != date) {
c = Calendar.getInstance();
c.setTime(date);
}
return c;
}
/**
* 获取指定日期的年份,若为 null,则返回当前时间的年份
*
* @param date
* @return
*/
public static int getYear(Date date) {
Calendar cal = Calendar.getInstance();
if (!Objects.isNull(date)) {
cal.setTime(date);
}
return cal.get(Calendar.YEAR);
}
/**
* 获取当前时间的小时
*
* @return
*/
public static int getHour() {
Date date = getNowDate();
Calendar cal = Calendar.getInstance();
if (!Objects.isNull(date)) {
cal.setTime(date);
}
return cal.get(Calendar.HOUR_OF_DAY);
}
/**
* 两日期比较,若某值为 null,则取当前时间
*
* @param souceDate
* @param targetDate
* @return
*/
public static Integer compareDate(Date souceDate, Date targetDate) {
if (null == souceDate || null == targetDate) {
return null;
}
return souceDate.compareTo(targetDate);
}
/**
* 获取指定日期之间的所有月份第一天
*
* @param startDate
* @param endDate
* @return
*/
public static List<Date> getMonthBetween(Date startDate, Date endDate) {
ArrayList<Date> result = new ArrayList<>();
Calendar min = Calendar.getInstance();
Calendar max = Calendar.getInstance();
min.setTime(startDate);
min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
max.setTime(endDate);
max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
Calendar curr = min;
while (curr.before(max)) {
result.add(curr.getTime());
curr.add(Calendar.MONTH, 1);
}
return result;
}
/**
* 将传过来的日期以 key-value 形式返回
*
* @param startDate
* @param endDate
* @return
*/
private static Map<Date, Date> getStartAndEndDateMap(Date startDate, Date endDate) {
Map<Date, Date> dateMap = new HashMap<>(2);
dateMap.put(startDate, endDate);
return dateMap;
}
/**
* 将制定日期 + 指定天数
*/
public static Date getDateAddNum(Date date, Integer num) {
date = DateUtil.parseDateYMD(DateUtil.toYMDString(date));
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DAY_OF_MONTH, +num);
return c.getTime();
}
/**
* 通过时间秒毫秒数判断两个时间的间隔+1天
*
* @param date1
* @param date2
* @return
*/
public static Integer daysBetween(Date date1, Date date2) {
long difference = (date1.getTime() - date2.getTime()) / 86400000;
return (int) Math.abs(difference) + 1;
}
/**
* 获取当前天的0点,精确到毫秒
*
* @return
*/
public static Date getNowDateInit() {
Calendar calendar1 = Calendar.getInstance();
calendar1.set(calendar1.get(Calendar.YEAR), calendar1.get(Calendar.MONTH), calendar1.get(Calendar.DAY_OF_MONTH),
0, 0, 0);
return parseDate(DateUtil.toYMDHSString(calendar1.getTime()));
}
/**
* 获取今天最后的时间:当天23:59:59
*
* @return
*/
public static Date getDayLastDate() {
return addSecond(addDay(getNowDateInit(), 1), -1);
}
/**
* 得到两个日期毫秒级差
*
* @param date0
* @param date1
* @return
*/
public static long getMillisecondDif(Date date0, Date date1) {
if (date0 == null || date1 == null) {
return 0;
}
return date0.getTime() - date1.getTime();
}
/**
* 得到两个日期秒级差
*
* @param date0
* @param date1
* @return
*/
public static long getSecondDif(Date date0, Date date1) {
return DateUtil.getMillisecondDif(date0, date1) / 1000;
}
/**
* 得到两个日期分钟差
*
* @param date0
* @param date1
* @return
*/
public static long getMinuteDif(Date date0, Date date1) {
return DateUtil.getSecondDif(date0, date1) / 60;
}
/**
* 得到两个日期小时差
*
* @param date0
* @param date1
* @return
*/
public static int getHourDif(Date date0, Date date1) {
return (int) DateUtil.getMinuteDif(date0, date1) / 60;
}
/**
* 根据日期获取指定日期的0点
*
* @param date
* @return
*/
public static Date initDateByDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH),
0, 0, 0);
return calendar.getTime();
}
/**
* 默认统计时间,转换成日期格式
*
* @return
*/
public static String countYesterday(String countDate, int num) {
if (StringUtils.isEmpty(countDate) || AppConstants.DEFAULT_DATE.equalsIgnoreCase(countDate)) {
countDate = toYMDString(addDay(initDateByDay(getNowDate()), num));
} else {
if (!validFormatter(countDate, DATE_FORMAT_YYYYMMDD)) {
throw new ApplicationException(ResultCode.DATE_FORMATTER_ERROR);
}
}
return countDate;
}
/**
* 验证日期类型
*
* @param date
* @param format
* @return
*/
public static boolean validFormatter(String date, String format) {
boolean flag = false;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
try {
LocalDate.parse(date, formatter);
flag = true;
} catch (DateTimeParseException | NullPointerException e) {
LOGGER.error("date Formatter is error");
}
return flag;
}
/**
* 积分按季度清空接口使用,返回下个季度初的第一个日期,截至日,时、分、秒是零
*
* @param localDate
* @return
*/
public static Date getQuarterDuration(LocalDate localDate) {
Calendar calendar = Calendar.getInstance();
switch (localDate.getMonth().firstMonthOfQuarter().getValue()) {
case 1:
calendar.set(localDate.getYear(), 3, 1);
break;
case 4:
calendar.set(localDate.getYear(), 6, 1);
break;
case 7:
calendar.set(localDate.getYear(), 9, 1);
break;
case 10:
calendar.set(localDate.plusYears(1).getYear(), 0, 1);
break;
default:
break;
}
return DateUtils.truncate(calendar.getTime(), Calendar.DATE);
}
/**
* 将日期格式化成中文的 “年+月+日+时”
* <p>
* 2020-01-01 15:00:00 → 2020年1月1日15时
*
* @param date
* @return
*/
public static String convertDateWithChinese(Date date) {
String dateStr = toYMDHSString(date);
return dateStr.substring(0, 4) + "年" +
(dateStr.substring(5, 7).startsWith("0") ?
dateStr.substring(5, 7).replace("0", "")
: dateStr.substring(5, 7)) + "月" +
(dateStr.substring(8, 10).startsWith("0") ?
dateStr.substring(8, 10).replace("0", "")
: dateStr.substring(8, 10)) + "日" +
(dateStr.substring(11, 13).startsWith("0") ?
dateStr.substring(11, 13).replace("0", "")
: dateStr.substring(11, 13)) + "时";
}
}