21 06 2019

日期操作工具类集合

今天有空遂整理了下最近做项目用到的日期操作工具类,做下记录,也供大家参考和指正。

注意:

本工具类为非线程安全的,多线程调用请根据实际情况自行修改

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
* @author will
* @2019/2/25 14:52
* 文件说明:日期时间操作工具类
*/
@Slf4j
public class TimeUtils {
/**
* 字符串转日期
*
* @param dateStr 日期字符串
* @param format 格式,比如yyyy-MM-dd HH:mm:ss、yyyy-MM-dd
* @return
*/
public static Date formatDate(String dateStr, String format) {
Date result = null;
try {
if (StringUtils.isBlank(dateStr)) {
throw new Exception("日期字符串不能为空");
}
if (StringUtils.isBlank(format)) {
throw new Exception("日期格式化格式不能为空");
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
result = sdf.parse(dateStr);
} catch (Exception e) {
log.error("字符串转日期异常 {}", e);
}
return result;
}

/**
* 日期转字符串
*
* @param dateStr 日期
* @param format 格式,比如yyyy-MM-dd HH:mm:ss、yyyy-MM-dd
* @return
*/
public static String formatSting(Date dateStr, String format) {
String result = null;
try {
if (null == dateStr) {
throw new Exception("日期不能为空");
}
if (StringUtils.isBlank(format)) {
throw new Exception("日期格式化格式不能为空");
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
result = sdf.format(dateStr);
} catch (Exception e) {
log.error("日期转字符串异常 {}", e);
}
return result;
}


/**
* 获取当前时间的上几周或者下几周某天日期
*
* @param n n为推迟的周数,0本周,-1向前推迟一周,1下周,依次类推
* @param week 想周几,这里就传几,请使用Calendar的常量,如Calendar.MONDAY(TUESDAY、WEDNESDAY...)
* @param date 日期
* @return
*/
public static String getBeforeAfterWeek(int n, int week, Date date) {
String monday = null;
try {
if (date == null) {
throw new Exception("日期不能为空");
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, n * 7);
cal.set(Calendar.DAY_OF_WEEK, week);
monday = formatSting(cal.getTime(), "yyyy-MM-dd");
} catch (Exception e) {
log.error("获取上周或下周某天日期失败 {}", e);
}
return monday;
}


/**
* 获取传入日期返回当月的最后一天的日期,如传入2018-6-11返回2018-6-30
*
* @param date 日期
* @return
*/
public static String getThisMothLastDay(Date date) {
String lastDayOfMonth = null;
try {
if (date == null) {
throw new Exception("日期不能为空");
}
Calendar thisMonthDayNum = Calendar.getInstance();
thisMonthDayNum.setTime(date);
//把日期设置为当月第一天
thisMonthDayNum.set(Calendar.DATE, 1);
//日期回滚一天,也就是最后一天
thisMonthDayNum.roll(Calendar.DATE, -1);
int lastDay = thisMonthDayNum.get(Calendar.DAY_OF_MONTH);
//设置日历中月份的最大天数
thisMonthDayNum.set(Calendar.DAY_OF_MONTH, lastDay);
//格式化日期
lastDayOfMonth = formatSting(thisMonthDayNum.getTime(), "yyyy-MM-dd");
} catch (Exception e) {
log.error("获取传入日期当月最后一天异常 {}", e);
}
return lastDayOfMonth;
}

/**
* 获取传入日期返回当月第一天的日期,如传入2018-6-11返回2018-6-01
*
* @param date 日期
* @return
*/
public static String getThisMothFirstDay(Date date) {
String lastDayOfMonth = null;
try {
if (date == null) {
throw new Exception("日期不能为空");
}
Calendar thisMonthDayNum = Calendar.getInstance();
thisMonthDayNum.setTime(date);
//把日期设置为当月第一天
thisMonthDayNum.set(Calendar.DATE, 1);
lastDayOfMonth = formatSting(thisMonthDayNum.getTime(), "yyyy-MM-dd");
} catch (Exception e) {
log.error("获取传入日期当月第一天异常 {}", e);
}
return lastDayOfMonth;
}

/**
* 获取传入日期上个月的最后一天,如传入2018-6-11返回2018-5-31
*
* @param date
* @return
*/
public static String getLastOneMothLastDay(Date date) {
String lastMonthStr = null;
try {
if (date == null) {
throw new Exception("日期不能为空");
}
Calendar lastMonthDay = Calendar.getInstance();
lastMonthDay.setTime(date);
lastMonthDay.set(Calendar.DAY_OF_MONTH, 1);
lastMonthDay.add(Calendar.DAY_OF_YEAR, -1);
lastMonthStr = DateFormatUtils.format(lastMonthDay, "yyyy-MM-dd");
} catch (Exception e) {
log.error("获取传入日期上个月最后一天异常 {}", e);
}
return lastMonthStr;
}


/**
* 获取传入日期上个月的第一天,如传入2018-6-11返回2018-5-1
*
* @param date
* @return
*/
public static String getLastOneMothFirstDay(Date date) {
String lastMonthStr = null;
try {
if (date == null) {
throw new Exception("日期不能为空");
}
Calendar lastMonthDay = Calendar.getInstance();
lastMonthDay.setTime(date);
lastMonthDay.set(Calendar.DAY_OF_MONTH, 1);
lastMonthDay.add(Calendar.DAY_OF_YEAR, -1);
//把日期设置为当月第一天
lastMonthDay.set(Calendar.DATE, 1);
lastMonthStr = DateFormatUtils.format(lastMonthDay, "yyyy-MM-dd");
} catch (Exception e) {
log.error("获取传入日期上个月第一天异常 {}", e);
}
return lastMonthStr;
}

/**
* 获取年某某月有多少天
*
* @param year
* @param month
* @return
*/
public static Integer dayNum(Integer year, Integer month) {
Integer day = null;
try {
Calendar c = Calendar.getInstance();
//输入类型为int类型
c.set(year, month, 0);
return c.get(Calendar.DAY_OF_MONTH);
} catch (NumberFormatException e) {
log.error("获取年某某月有多少天异常 {}", e);
}
return day;
}


/**
* 获得本周一与当前日期相差的天数
*
* @return
*/
public static int getMondayPlus() {
Calendar cd = Calendar.getInstance();
int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == 1) {
return -6;
} else {
return 2 - dayOfWeek;
}
}


/**
* 获得当前周周一的日期
*
* @return
*/
public static String getCurrentMonday() {
int mondayPlus = getMondayPlus();
GregorianCalendar currentDate = new GregorianCalendar();
currentDate.add(GregorianCalendar.DATE, mondayPlus);
Date monday = currentDate.getTime();
String preMonday = formatSting(monday, "yyyy-MM-dd");
return preMonday;
}

/**
* 获得当前周周日的日期
*
* @return
*/
public static String getPreviousSunday() {
int mondayPlus = getMondayPlus();
GregorianCalendar currentDate = new GregorianCalendar();
currentDate.add(GregorianCalendar.DATE, mondayPlus + 6);
Date monday = currentDate.getTime();
String preMonday = formatSting(monday, "yyyy-MM-dd");
return preMonday;

}

/**
* 获取当前系统前一天日期
*
* @return
*/
public static String getBeforeOneDay() {
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, -1);
date = calendar.getTime();
String day = DateFormatUtils.format(date, "yyyy-MM-dd");
return day;
}

/**
* 获得指定日期的前一天
*
* @param specifiedDay
* @return
* @throws Exception
*/
public static String getSpecifiedDayBefore(String specifiedDay) {
String dayBefore = null;
try {
Calendar c = Calendar.getInstance();
Date date = null;
date = formatDate(specifiedDay, "yy-MM-dd");
c.setTime(date);
int day = c.get(Calendar.DATE);
c.set(Calendar.DATE, day - 1);
dayBefore = formatSting(c.getTime(), "yyyy-MM-dd");
} catch (Exception e) {
log.error("获得指定日期的前一天异常 {}", e);
}
return dayBefore;
}


/**
* 获得指定日期本周一的日期
*
* @param time
* @return
*/
public static String getWeekFirst(String time) {
String data1 = null;
try {
Calendar cal = Calendar.getInstance();
cal.setTime(formatDate(time, "yyyy-MM-dd"));
int d = 0;
if (cal.get(Calendar.DAY_OF_WEEK) == 1) {
d = -6;
} else {
d = 2 - cal.get(Calendar.DAY_OF_WEEK);
}
cal.add(Calendar.DAY_OF_WEEK, d);
// 所在周开始日期
data1 = formatSting(cal.getTime(), "yyyy-MM-dd");
} catch (Exception e) {
log.error("获得指定日期周一异常 {}", e);
}
return data1;
}

/**
* 获得指定日期本周日的日期
*
* @param time
* @return
*/
public static String getWeekLast(String time) {
String imptimeMi = null;
try {
Calendar cal = Calendar.getInstance();
cal.setTime(formatDate(time, "yyyy-MM-dd"));
//判断要计算的日期是否是周日,如果是则减一天计算周六的,否则会出问题,计算到下一周去了
//获得当前日期是一个星期的第几天
int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
if (1 == dayWeek) {
cal.add(Calendar.DAY_OF_MONTH, -1);
}
//设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
cal.setFirstDayOfWeek(Calendar.MONDAY);
//获得当前日期是一个星期的第几天
int day = cal.get(Calendar.DAY_OF_WEEK);
//根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
cal.add(Calendar.DATE, 6);
imptimeMi = formatSting(cal.getTime(), "yyyy-MM-dd");
} catch (Exception e) {
log.error("获得指定日期本周日的日期异常 {}", e);
}
return imptimeMi;
}

/**
* 获得指定日期周一,动态加减天数
*
* @param time
* @param num 加减天数,减则为-
* @return
*/
public static String getTuesday(String time, int num) {
String imptimeMi = null;
try {
Calendar cal = Calendar.getInstance();
cal.setTime(formatDate(time, "yyyy-MM-dd"));
//判断要计算的日期是否是周日,如果是则减一天计算周六的,否则会出问题,计算到下一周去了
//获得当前日期是一个星期的第几天
int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
if (1 == dayWeek) {
cal.add(Calendar.DAY_OF_MONTH, -1);
}
//设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
cal.setFirstDayOfWeek(Calendar.MONDAY);
//获得当前日期是一个星期的第几天
int day = cal.get(Calendar.DAY_OF_WEEK);
//根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
cal.add(Calendar.DATE, num);
imptimeMi = formatSting(cal.getTime(), "yyyy-MM-dd");
} catch (Exception e) {
log.error("获得指定日期周一,动态加减天数,异常 {}", e);
}
return imptimeMi;
}

/**
* 获取某个日期当天的开始时间,2019-05-10 00:00:00.0
*
* @param d
* @return
*/
public static Timestamp getDayStartTime(Date d) {
Calendar calendar = Calendar.getInstance();
if (null != d) calendar.setTime(d);
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
calendar.set(Calendar.MILLISECOND, 0);
return new Timestamp(calendar.getTimeInMillis());
}


/**
* 获取某个日期当天的结束时间,2019-05-10 23:59:59.999
*
* @param d
* @return
*/
public static Timestamp getDayEndTime(Date d) {
Calendar calendar = Calendar.getInstance();
if (null != d) calendar.setTime(d);
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
calendar.set(Calendar.MILLISECOND, 999);
return new Timestamp(calendar.getTimeInMillis());
}


/**
* 获取指定日期上周的开始时间
*
* @param time
* @return
*/
public static String getBeginDayOfLastWeek(String time) {
String r = null;
try {
if (time == null) {
throw new Exception("日期不能为空");
}
Calendar cal = Calendar.getInstance();
cal.setTime(formatDate(time, "yyyy-MM-dd"));
int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
if (dayofweek == 1) {
dayofweek += 7;
}
cal.add(Calendar.DATE, 2 - dayofweek - 7);
r = formatSting(cal.getTime(), "yyyy-MM-dd");
} catch (Exception e) {
log.error("获取指定日期上周的开始时间异常 {}", e);
}
return r;
}

/**
* 获取指定日期上周的结束时间
*
* @param time
* @return
*/
public static String getEndDayOfLastWeek(String time) {
String day = null;
try {
if (time == null) {
throw new Exception("日期不能为空");
}
Calendar cal = Calendar.getInstance();
cal.setTime(formatDate(getBeginDayOfLastWeek(time), "yyyy-MM-dd"));
cal.add(Calendar.DAY_OF_WEEK, 6);
Date weekEndSta = cal.getTime();
day = formatSting(weekEndSta, "yyyy-MM-dd");
} catch (Exception e) {
log.error("获取指定日期上周的结束时间异常 {}", e);
}
return day;
}


/**
* 给定某日期,判断是星期几
*
* @param date
* @return
*/
public static String getTimeToWeek(String date) {
SimpleDateFormat sdw = null;
Date d = null;
try {
if (date == null) {
throw new Exception("日期不能为空");
}
sdw = new SimpleDateFormat("E");
d = null;
d = formatDate(date, "yyyy-MM-dd");
} catch (Exception e) {
log.error("给定某日期,判断是星期几异常 {}", e);
}
return sdw.format(d);
}


/**
* 通过时间秒毫秒数判断两个时间的间隔
*
* @param date1
* @param date2
* @return
*/
public static int differentDaysByMillisecond(Date date1, Date date2) {
int days = (int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24));
return days;
}


/**
* 获取两个日期之间的日期,包括开始结束日期
*
* @param start 开始日期
* @param end 结束日期
* @return 日期集合
*/
public static List<Date> getBetweenDates(Date start, Date end) {
List<Date> result = new ArrayList<Date>();
Calendar tempStart = Calendar.getInstance();
tempStart.setTime(start);
tempStart.add(Calendar.DAY_OF_YEAR, 1);
Calendar tempEnd = Calendar.getInstance();
tempEnd.setTime(end);
result.add(start);
while (tempStart.before(tempEnd)) {
result.add(tempStart.getTime());
tempStart.add(Calendar.DAY_OF_YEAR, 1);
}
result.add(end);
return result;
}


/**
* 日期转时间戳
*
* @param date
* @return
*/
public static Integer transForMilliSecond(Date date) {
try {
if (date == null) throw new Exception("日期不能为空");
} catch (Exception e) {
e.printStackTrace();
}
return (int) (date.getTime() / 1000);
}


/**
* 日期字符串转时间戳,可动态加减日期
*
* @param dateStr
* @return
*/
public static Integer transForMilliSecond2(String dateStr, int num) {
Date date = TimeUtils.formatDate(dateStr, "yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, num);
return date == null ? null : TimeUtils.transForMilliSecond(calendar.getTime());
}

/**
* 日期字符串动态加减日期
*
* @param dateStr
* @return
*/
public static String timeAddSub(String dateStr, int num) {
Date date = TimeUtils.formatDate(dateStr, "yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, num);
Date date1 = calendar.getTime();
return TimeUtils.formatSting(date1, "yyyy-MM-dd");
}

/**
* 日期字符串动态加减日期
*
* @param dateStr
* @param num
* @param fomt 格式
* @return
*/
public static String timeAddSub(String dateStr, int num, String fomt) {
Date date = TimeUtils.formatDate(dateStr, fomt);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, num);
Date date1 = calendar.getTime();
return TimeUtils.formatSting(date1, fomt);
}

}

如果文章对你有用请评论或点个赞,顶上去让更多人看到,少踩坑,谢谢(疯狂暗示)  

延伸阅读
  1. 博客第一个版本已经好了,欢迎各位体验测试
  2. Spring+Websocket相遇、相知、相爱、相杀(附源码和在线演示)
发表评论