注:示例未全部测试,请使用者自行测试!!!
本示例为基于calendar类实现的,1.8版本后引入了新的时间工具类,以下为示例:
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String dateTime = dateTimeFormatter.format(LocalDateTime.now());
以下为工具正文
部分方法需要commons-lang3和slf4j jar包
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* <p>
* Date Operation Utils
* </p>
*
* @author IceWee
* @see org.apache.commons.lang3.time.DateUtils
* @see org.apache.commons.lang3.time.FastDateFormat
* @see org.apache.commons.lang3.time.DateFormatUtils
*/
public class DateUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(DateUtil.class);
/**
* zero - 0
*/
public static final int ZERO = 0;
/**
* max hour
*/
public static final int MAX_HOUR = 23;
/**
* max minute
*/
public static final int MAX_MINUTE = 59;
/**
* max second
*/
public static final int MAX_SECOND = 59;
/**
* max millisecond
*/
public static final int MAX_MILLISECOND = 999;
/**
* days of one week
*/
public static final int DAYS_OF_WEEK = 7;
/**
* default date pattern
*/
public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";
public static final String PATTERN_CLASSICAL_SIMPLE = "yyyy-MM-dd";
/**
* default datetime pattern
*/
public static final String DEFAULT_DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
/**
* default date/datetime patterns
*/
public static final String[] DEFAULT_PATTERNS = new String[]{"yyyy-MM-dd HH:mm:ss.S", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd", "yyyy-MM", "yyyy/MM/dd HH:mm:ss.S",
"yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM/dd", "yyyy/MM", "yyyyMMddHHmmss", "yyyyMMddHHmm", "yyyyMMdd", "yyyyMM", "MM-dd-yyyy", "MM/dd/yyyy", "dd/MM/yyyy"};
public static final int DAY_SECONDS = 24 * 60 * 60;
public static final long DAY_MILLISECONDS = DAY_SECONDS * 1000L;
private DateUtil() {
super();
}
/**
* <p>
* Parses a object representing a date by trying a variety of different parsers.
* </p>
* <p>
* <p>
* The parse will try each parse pattern in turn. A parse is only deemed successful if it parses the whole of the input string. If no parse
* patterns match, a ParseException is thrown.
* </p>
* The parser will be lenient toward the parsed date.
*
* @param obj the date to parse, may be null
* @param parsePatterns the date format patterns to use, see SimpleDateFormat, not null
* @return the parsed date or null
* @throws ParseException if none of the date patterns were suitable (or there were none)
*/
public static Date parseDate(final Object obj, final String... parsePatterns) throws ParseException {
Date date = null;
if (obj != null) {
date = DateUtils.parseDate(Objects.toString(obj), parsePatterns);
}
return date;
}
/**
* <p>
* Formats a date/calendar/long into a specific pattern.
* </p>
*
* @param obj the {@code Date}/{@code Calendar}/{@code Long} to format, may be null
* @param pattern the pattern to use to format the date, may be null
* @return the formatted date or null
*/
public static String format(final Object obj, final String pattern) {
String str = null;
if (obj != null) {
if (obj instanceof Date) {
str = formatDate((Date) obj, pattern);
} else if (obj instanceof Calendar) {
str = formatCalendar((Calendar) obj, pattern);
} else if (obj instanceof Long) {
str = formatMillis((Long) obj, pattern);
}
}
return str;
}
public static String format(Date date) {
if ("".equals(date) || date == null) {
date = new Date();
}
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
}
/**
* <p>
* Formats a date/time/timestamp into a specific pattern.
* </p>
*
* @param date the date to format, may be null
* @param pattern the pattern to use to format the date, may be null
* @return the formatted date or null
*/
public static String formatDate(final Date date, final String pattern) {
String str = null;
if (date != null && StringUtils.isNotBlank(pattern)) {
str = DateFormatUtils.format(date, pattern);
}
return str;
}
/**
* <p>
* Formats a calendar into a specific pattern.
* </p>
*
* @param calendar the calendar to format, may be null
* @param pattern the pattern to use to format the calendar, may be null
* @return the formatted calendar or null
* @see FastDateFormat#format(Calendar)
*/
public static String formatCalendar(final Calendar calendar, final String pattern) {
String str = null;
if (calendar != null && StringUtils.isNotBlank(pattern)) {
str = DateFormatUtils.format(calendar, pattern);
}
return str;
}
/**
* <p>
* Formats a date/time into a specific pattern.
* </p>
*
* @param millis the date to format expressed in milliseconds
* @param pattern the pattern to use to format the date, not null
* @return the formatted date or null
*/
public static String formatMillis(final Long millis, final String pattern) {
String str = null;
if (millis != null && StringUtils.isNotBlank(pattern)) {
str = DateFormatUtils.format(millis, pattern);
}
return str;
}
/**
* <p>
* Gets Monday of current week
* </p>
*
* @return {@code Date} Monday of current week
*/
public static Date getMonday() {
return getWeekday(Calendar.MONDAY);
}
/**
* <p>
* Gets Monday of current week
* </p>
*
* @param firstDayOfWeek Monday or Sunday
* @return {@code Date} Monday of current week
*/
public static Date getMonday(final int firstDayOfWeek) {
return getWeekday(Calendar.MONDAY, firstDayOfWeek);
}
/**
* <p>
* Gets Monday of specified date's own week
* </p>
*
* @param date may be null
* @return {@code Date} Monday or null
*/
public static Date getMonday(final Date date) {
return getWeekday(Calendar.MONDAY, date);
}
/**
* <p>
* Gets Monday of specified date's own week
* </p>
*
* @param firstDayOfWeek Monday or Sunday
* @param date may be null
* @return {@code Date} Monday or null
*/
public static Date getMonday(final int firstDayOfWeek, final Date date) {
return getWeekday(Calendar.MONDAY, firstDayOfWeek, date);
}
/**
* <p>
* Gets Sunday of current week
* </p>
*
* @return {@code Date} Sunday of current week
*/
public static Date getSunday() {
return getWeekday(Calendar.SUNDAY);
}
/**
* <p>
* Gets Sunday of current week
* </p>
*
* @param firstDayOfWeek Monday or Sunday
* @return {@code Date} Sunday of current week
*/
public static Date getSunday(final int firstDayOfWeek) {
return getWeekday(Calendar.SUNDAY, firstDayOfWeek);
}
/**
* <p>
* Gets Sunday of specified date's own week, first day of week is Monday by default
* </p>
*
* @param date may be null
* @return {@code Date} Sunday or null
*/
public static Date getSunday(final Date date) {
return getWeekday(Calendar.SUNDAY, date);
}
/**
* <p>
* Gets Sunday of specified date's own week
* </p>
*
* @param firstDayOfWeek Monday or Sunday
* @param date may be null
* @return {@code Date} Sunday or null
*/
public static Date getSunday(final int firstDayOfWeek, final Date date) {
return getWeekday(Calendar.SUNDAY, firstDayOfWeek, date);
}
/**
* <p>
* Gets weekday of current week
* </p>
*
* @param dayOfWeek Monday to Sunday
* @return {@code Date} weekday of current week
* @see Calendar#SUNDAY
* @see Calendar#MONDAY
* @see Calendar#TUESDAY
* @see Calendar#WEDNESDAY
* @see Calendar#THURSDAY
* @see Calendar#FRIDAY
* @see Calendar#SATURDAY
*/
public static Date getWeekday(final int dayOfWeek) {
return getWeekday(dayOfWeek, new Date());
}
/**
* <p>
* Gets weekday of current week
* </p>
*
* @param dayOfWeek Monday to Sunday
* @param firstDayOfWeek Monday or Sunday
* @return {@code Date} weekday of current week
* @see Calendar#SUNDAY
* @see Calendar#MONDAY
* @see Calendar#TUESDAY
* @see Calendar#WEDNESDAY
* @see Calendar#THURSDAY
* @see Calendar#FRIDAY
* @see Calendar#SATURDAY
*/
public static Date getWeekday(final int dayOfWeek, final int firstDayOfWeek) {
return getWeekday(dayOfWeek, firstDayOfWeek, new Date());
}
/**
* <p>
* Gets weekday of specified date's own week, first day of week is Monday by default
* </p>
*
* @param dayOfWeek
* @param date may be null
* @return {@code Date} weekday or null
* @see Calendar#SUNDAY
* @see Calendar#MONDAY
* @see Calendar#TUESDAY
* @see Calendar#WEDNESDAY
* @see Calendar#THURSDAY
* @see Calendar#FRIDAY
* @see Calendar#SATURDAY
*/
public static Date getWeekday(final int dayOfWeek, final Date date) {
return getWeekday(dayOfWeek, Calendar.MONDAY, date);
}
/**
* <p>
* Gets weekday of specified date's own week
* </p>
*
* @param dayOfWeek Monday to Sunday
* @param firstDayOfWeek Monday or Sunday
* @param date may be null
* @return {@code Date} weekday or null
* @see Calendar#SUNDAY
* @see Calendar#MONDAY
* @see Calendar#TUESDAY
* @see Calendar#WEDNESDAY
* @see Calendar#THURSDAY
* @see Calendar#FRIDAY
* @see Calendar#SATURDAY
*/
public static Date getWeekday(final int dayOfWeek, final int firstDayOfWeek, final Date date) {
Date weekday = null;
if (date != null) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.setFirstDayOfWeek(firstDayOfWeek);
calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek);
weekday = calendar.getTime();
}
return weekday;
}
/**
* <p>
* Gets first day of current month
* </p>
*
* @return {@code Date} first day
*/
public static Date getFirstDayOfMonth() {
return getFirstDayOfMonth(new Date());
}
/**
* <p>
* Gets first day of specified date's own month
* </p>
*
* @param date may be null
* @return {@code Date} first day or null
*/
public static Date getFirstDayOfMonth(final Date date) {
Date firstDay = null;
if (date != null) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
setBeginTime(calendar);
firstDay = calendar.getTime();
}
return firstDay;
}
/**
* <p>
* Gets last day of current month
* </p>
*
* @return {@code Date} last day
*/
public static Date getLastDayOfMonth() {
return getLastDayOfMonth(new Date());
}
/**
* <p>
* Gets last day of specified date's own month
* </p>
*
* @param date may be null
* @return {@code Date} last day
*/
public static Date getLastDayOfMonth(final Date date) {
Date lastDay = null;
if (date != null) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
setEndTime(calendar);
lastDay = calendar.getTime();
}
return lastDay;
}
/**
* <p>
* Gets first day of current year
* </p>
*
* @return {@code Date} first day
*/
public static Date getFirstDayOfYear() {
return getFirstDayOfYear(new Date());
}
/**
* <p>
* Gets first day of specified date's own year
* </p>
*
* @param date may be null
* @return {@code Date} first day or null
*/
public static Date getFirstDayOfYear(final Date date) {
Date firstDay = null;
if (date != null) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
setBeginTime(calendar);
firstDay = calendar.getTime();
}
return firstDay;
}
/**
* <p>
* Gets last day of current year
* </p>
*
* @return {@code Date} last day
*/
public static Date getLastDayOfYear() {
return getLastDayOfYear(new Date());
}
/**
* <p>
* Gets last day of specified date's own year
* </p>
*
* @param date may be null
* @return {@code Date} last day or null
*/
public static Date getLastDayOfYear(final Date date) {
Date lastDay = null;
if (date != null) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.MONTH, Calendar.DECEMBER);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
setEndTime(calendar);
lastDay = calendar.getTime();
}
return lastDay;
}
/**
* <p>
* Gets first time of {@code date}
* </p>
*
* @param date may be null
* @return {@code Date} first time 00:00:00 or null
*/
public static Date getBeginTimeOfDate(final Date date) {
Date beginTime = null;
if (date != null) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
setBeginTime(calendar);
beginTime = calendar.getTime();
}
return beginTime;
}
/**
* <p>
* Gets end time of {@code date}
* </p>
*
* @param date may be null
* @return {@code Date} end time 23:59:59 or null
*/
public static Date getEndTimeOfDate(final Date date) {
Date endTime = null;
if (date != null) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
setEndTime(calendar);
endTime = calendar.getTime();
}
return endTime;
}
/**
* <p>
* Gets {@code days} days before of {@code date}
* </p>
*
* @param date may be null
* @param days
* @return {@code Date} some days before or null
*/
public static Date beforeDays(final Date date, final int days) {
Date daysBefore = date;
if (days > ZERO && date != null) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_YEAR, -days);
daysBefore = calendar.getTime();
}
return daysBefore;
}
/**
* <p>
* Gets {@code days} days after of {@code date}
* </p>
*
* @param date may be null
* @param days
* @return {@code Date} some days after or null
*/
public static Date afterDays(final Date date, final int days) {
Date daysAfter = date;
if (days > ZERO && date != null) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_YEAR, days);
daysAfter = calendar.getTime();
}
return daysAfter;
}
/**
* <p>
* Gets {@code weeks} weeks before of {@code date}
* </p>
*
* @param date may be null
* @param weeks
* @return {@code Date} some weeks before or null
*/
public static Date beforeWeeks(final Date date, final int weeks) {
return beforeDays(date, weeks * DAYS_OF_WEEK);
}
/**
* <p>
* Gets {@code weeks} weeks after of {@code date}
* </p>
*
* @param date may be null
* @param weeks
* @return {@code Date} some weeks after or null
*/
public static Date afterWeeks(final Date date, final int weeks) {
return afterDays(date, weeks * DAYS_OF_WEEK);
}
/**
* <p>
* Sets time 00:00:00
* </p>
*
* @param calendar may be null
*/
private static void setBeginTime(final Calendar calendar) {
if (calendar != null) {
calendar.set(Calendar.HOUR_OF_DAY, ZERO);
calendar.set(Calendar.MINUTE, ZERO);
calendar.set(Calendar.SECOND, ZERO);
calendar.set(Calendar.MILLISECOND, ZERO);
}
}
/**
* <p>
* Sets time 23:59:59
* </p>
*
* @param calendar may be null
*/
private static void setEndTime(final Calendar calendar) {
if (calendar != null) {
calendar.set(Calendar.HOUR_OF_DAY, MAX_HOUR);
calendar.set(Calendar.MINUTE, MAX_MINUTE);
calendar.set(Calendar.SECOND, MAX_SECOND);
calendar.set(Calendar.MILLISECOND, MAX_MILLISECOND);
}
}
/**
* 获得上个月日期
*
* @return
*/
public static Date getLastDate() {
return getLastDate(new Date());
}
public static Date getLastDate(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, -1);
return cal.getTime();
}
public static Date addDays(Date date, int days) {
if (null != date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DATE, 1);
return c.getTime();
}
return null;
}
public static Date addOneDay(Date date) {
return addDays(date, 1);
}
/**
* 根据指定格式将指定字符串解析成日期
*
* @param str 指定日期
* @param pattern 指定格式
* @return 返回解析后的日期
*/
public static Date parse(String str, String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
try {
return sdf.parse(str);
} catch (ParseException e) {
LOGGER.error("date parse error", e);
}
return null;
}
/**
* 获取指定日期累加指定天数后的时间
*
* @param date 指定日期
* @param day 指定天数
* @return 返回累加天数后的时间
*/
public static Date rollDay(Date date, int day) {
return rollDate(date, 0, 0, day);
}
/**
* 获取指定日期累加年月日后的时间
*
* @param date 指定日期
* @param year 指定年数
* @param month 指定月数
* @param day 指定天数
* @return 返回累加年月日后的时间
*/
public static Date rollDate(Date date, int year, int month, int day) {
Calendar cal = Calendar.getInstance();
if (date != null) {
cal.setTime(date);
}
cal.add(Calendar.YEAR, year);
cal.add(Calendar.MONTH, month);
cal.add(Calendar.DAY_OF_MONTH, day);
return cal.getTime();
}
public static int getOffsetMinutes(Date date1, Date date2) {
return getOffsetSeconds(date1, date2) / 60;
}
/**
* 获取时间date1与date2相差的秒数
*
* @param date1 起始时间
* @param date2 结束时间
* @return 返回相差的秒数
*/
public static int getOffsetSeconds(Date date1, Date date2) {
return (int) ((date2.getTime() - date1.getTime()) / 1000);
}
public static String getDiffTime(long begin, long end) {
long diff = end - begin;
if (diff < 1000) {
return diff + "毫秒";
}
long day = diff / (24 * 60 * 60 * 1000);
long hour = (diff / (60 * 60 * 1000) - day * 24);
long min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
long sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
return String.format("%s%s %s分 %s秒", hour > 0 ? hour : "", hour > 0 ? "小时" : "", min, sec);
}
/**
* 当前时间到本周日结束的时间差秒数
*
* @return 秒数
*/
public static Long getTimeDiffToSundayEnd() {
Date sunday = DateUtil.getSunday();
sunday.setHours(0);
sunday.setMinutes(0);
sunday.setSeconds(0);
Calendar sundayEnd = Calendar.getInstance();
sundayEnd.setTime(sunday);
sundayEnd.add(Calendar.DAY_OF_WEEK, 1);
System.out.println(sundayEnd.getTimeInMillis());
Long timeDiff = sundayEnd.getTimeInMillis() - System.currentTimeMillis();
return timeDiff / 1000;
}
public static Date getDate(Date date, int num) {
if (num == 3) {
return date;
}
Calendar src = Calendar.getInstance();
src.setTime(DateUtil.afterDays(date, 1));
int nums = checkDateIsWorkDay(src);
if (nums == 0 || nums == 3) {
num++;
}
return getDate(DateUtil.afterDays(date, 1), num);
}
private static Map<String, String> map = new HashMap<>();
private static void initHolidayData() {
map.put("20170930", "1");
map.put("20171001", "0");
map.put("20171002", "0");
map.put("20171003", "0");
map.put("20171004", "0");
map.put("20171005", "0");
map.put("20171006", "0");
map.put("20171007", "0");
map.put("20171008", "0");
}
/**
* 检查当前日期是 周六日 还是节假日 还是工作日 0 代表工作日 1 代表周六日 2 代表补班 3代表休假
*
* @param src 日期
* @return 返回判断类型
*/
private static int checkDateIsWorkDay(Calendar src) {
int result = 0;
if (map.isEmpty()) {
//初始化数据
initHolidayData();
}
//先检查是否是周六周日(有些国家是周五周六)
if (src.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY
|| src.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
result = 1;
}
// 检查 国家节假日
Set<Map.Entry<String, String>> holiDayMap = map.entrySet();
String day = DateUtil.formatCalendar(src, "yyyyMMdd");
for (Map.Entry<String, String> entry : holiDayMap) {
if (entry.getKey().equals(day) && entry.getValue().equals("0")) {
result = 2;
} else if (entry.getKey().equals(day) && entry.getValue().equals("1")) {
result = 3;
}
}
return result;
}
/**
* 计算两个日期相差多少秒
*
* @param start 开始日期
* @param end 结束日期
* @return 相差秒数
*/
public static int getDateDiffer(Date start, Date end) {
return (int) (end.getTime() - start.getTime()) / 1000;
}
/**
* 获取指定日期的开始时间点
*
* @param date 指定日期
* @return 开始日期字符串 格式:yyyy-MM-dd 00:00:00
*/
public static String getStartDate(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date zero = calendar.getTime();
return DateUtil.formatDate(zero, DateUtil.DEFAULT_DATETIME_PATTERN);
}
/**
* 获取指定日期的截止时间点
*
* @param date 指定日期
* @return 结束时间字符串 格式:yyyy-MM-dd 23:59:59
*/
public static String getEndDate(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
Date zero = calendar.getTime();
return DateUtil.formatDate(zero, DateUtil.DEFAULT_DATETIME_PATTERN);
}
/**
* 计算两个日期的0点相差天数是否小于等于days
*
* @param from 开始日期
* @param to 结束日期
* @param days 天数
* @return
*/
public static boolean intervalDays(Date from, Date to, int days) {
if (from == null || to == null) {
return false;
}
// long fromTime = from.getTime();
// long toTime = to.getTime();
//
// return Math.abs(fromTime - toTime) < days * DateUtils.MILLIS_PER_DAY;
return Math.abs(intervalDays(from, to)) < days;
}
/**
* 计算两个时间之间的天数差,按照自然日计算
*
* @param begin 开始时间
* @param end 结束时间
* @return 相差的天数
*/
public static long intervalDays(Date begin, Date end) {
if (begin == null || end == null) {
return 0;
}
begin = DateUtils.truncate(begin, Calendar.DATE);
end = DateUtils.truncate(end, Calendar.DATE);
return (end.getTime() - begin.getTime()) / DAY_MILLISECONDS;
}
}