仅供参考,收录了一些常用的java中关于时间的处理方法,希望能帮到你!
import org.apache.commons.lang3.time.DateFormatUtils;
import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.TimeZone;
/**
* 时间工具类
*
* @author wyc
*/
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
public static String YYYY = "yyyy";
public static String YYYY_MM = "yyyy-MM";
public static String YYYY_MM_DD = "yyyy-MM-dd";
public static String YYYY_MM_DD_ = "yyyy年-MM月-dd日";
public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
private static String[] parsePatterns = {
"yyyy-MM-dd"
, "yyyy-MM-dd HH:mm:ss"
, "yyyy-MM-dd HH:mm"
, "yyyy-MM"
, "yyyy/MM/dd"
, "yyyy/MM/dd HH:mm:ss"
, "yyyy/MM/dd HH:mm"
, "yyyy/MM"
, "yyyy.MM.dd"
, "yyyy.MM.dd HH:mm:ss"
, "yyyy.MM.dd HH:mm"
, "yyyy.MM"
};
/**
* 计算两个时间差
* 指定日期加上天数后的日期 Date类型
*
* @param endDate
* @param nowDate 创建时间
* @return
* @throws ParseException
*/
public static String retDatePoor(Date endDate, Date nowDate) {
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
// long ns = 1000;
// 获得两个时间的毫秒时间差异
long diff = endDate.getTime() - nowDate.getTime();
// 计算差多少天
long day = diff / nd;
// 计算差多少小时
long hour = diff % nd / nh;
// 计算差多少分钟
long min = diff % nd % nh / nm;
// 计算差多少秒//输出结果
// long sec = diff % nd % nh % nm / ns;
return day + "天" + hour + "小时" + min + "分钟";
}
/**
* 获取当前Date型日期
*
* @return Date() 当前日期
*/
public static Date getNowDate() {
return new Date();
}
/**
* 计算相差天数
*/
public static int differentDaysByMillisecond(Date date1, Date date2) {
return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
}
/**
* 获取当前日期, 默认格式为yyyy-MM-dd
*
* @return String
*/
public static String getDate() {
return dateTimeNow(YYYY_MM_DD);
}
public static final String getTime() {
return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
}
public static final String dateTimeNow() {
return dateTimeNow(YYYYMMDDHHMMSS);
}
public static final String dateTimeNow(final String format) {
return parseDateToStr(format, new Date());
}
public static final String dateTime(final Date date) {
return parseDateToStr(YYYY_MM_DD, date);
}
public static final String parseDateToStr(final String format, final Date date) {
return new SimpleDateFormat(format).format(date);
}
public static final Date dateTime(final String format, final String ts) {
try {
return new SimpleDateFormat(format).parse(ts);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
/**
* 日期路径 即年/月/日 如2018/08/08
*/
public static final String datePath() {
Date now = new Date();
return DateFormatUtils.format(now, "yyyy/MM/dd");
}
/**
* 日期路径 即年/月/日 如20180808
*/
public static final String dateTime() {
Date now = new Date();
return DateFormatUtils.format(now, "yyyyMMdd");
}
/**
* 日期型字符串转化为日期 格式
*/
public static Date parseDate(Object str) {
if (str == null) {
return null;
}
try {
return parseDate(str.toString(), parsePatterns);
} catch (ParseException e) {
return null;
}
}
/**
* 获取服务器启动时间
*/
public static Date getServerStartDate() {
long time = ManagementFactory.getRuntimeMXBean().getStartTime();
return new Date(time);
}
/**
* 计算两个时间差
*/
public static HashMap<String, Integer> getDatePoor(Date endDate, Date nowDate) {
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
// long ns = 1000;
// 获得两个时间的毫秒时间差异
long diff = endDate.getTime() - nowDate.getTime();
// 计算差多少天
long day = diff / nd;
// 计算差多少小时
long hour = diff % nd / nh;
// 计算差多少分钟
long min = diff % nd % nh / nm;
// 计算差多少秒//输出结果
// long sec = diff % nd % nh % nm / ns;
HashMap<String, Integer> map = new HashMap<>();
map.put("day", (int) day);//天
map.put("hour", (int) hour);//小时
map.put("min", (int) min);//分
return map;
}
public static final long getTimestamp() {
return System.currentTimeMillis() / 1000;
}
/**
* 获取当前时间指定天数后的时间
*
* @return
*/
public static Date getsSpecifiedRearDayTime(Integer day) {
//不能超过 且不能等于30天
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(getNowDate().getTime() + 3600 * 24 * 1000 * day);
return cal.getTime();
}
/**
* 指定时间指定年数的时间
*
* @return
*/
public static Date addDateYear(Date date, Integer year) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);//设置起时间
cal.add(Calendar.YEAR, year);//增加指定年数
return cal.getTime();
}
/**
* 指定时间指定月数的时间
*
* @return
*/
public static Date addDateMonth(Date date, Integer month) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);//设置起时间
cal.add(Calendar.MONTH, month);//增加指定年数
return cal.getTime();
}
/**
* 指定天数增加天数
*
* @return
*/
public static Date addDateDay(Date date, Integer day) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);//设置起时间
cal.add(Calendar.DATE, day);//增加指定年数
return cal.getTime();
}
/**
* 判断是否超过24小时
*
* @param date1
* @param date2
* @return boolean
* @throws Exception
*/
public static boolean judgmentDate(Date date1, Date date2) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d HH:mm:ss");
long cha = date1.getTime() - date2.getTime();
System.out.println(cha);
if (cha < 0) {
//零点到八点之间,返回true
if (cha >= -60 * 60 * 1000 * 8) {
return true;
}
return false;
}
double result = cha * 1.0 / (1000 * 60 * 60);
if (result <= 24) {
return true;
} else {
return false;
}
}
/**
* @MethodName: stringToDate
* @Description: 字符串日期格式化date类型
* @Param: [dateStr, date]
* @Return: java.util.Date
* @Author: wyc
* @Date: 2020/5/10 15:37
**/
public static Date stringToDate(String dateStr, String pattern) {
SimpleDateFormat format = new SimpleDateFormat(pattern);
Date date = null;
try {
date = format.parse(dateStr);
} catch (ParseException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
return date;
}
/**
* 指定日期加上天数后的日期 string类型
*
* @param num 为增加的天数
* @param newDate 创建时间
* @return
* @throws ParseException
*/
public static String plusStrDay(int num, String newDate) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currdate = format.parse(newDate);
System.out.println("现在的日期是:" + currdate);
Calendar ca = Calendar.getInstance();
ca.setTime(currdate);
ca.add(Calendar.DATE, num);// num为增加的天数,可以改变的
currdate = ca.getTime();
String enddate = format.format(currdate);
System.out.println("增加天数以后的日期:" + enddate);
return enddate;
}
/**
* 指定日期加上天数后的日期 Date类型
*
* @param num 为增加的天数
* @param newDate 创建时间
* @return
* @throws ParseException
*/
public static Date plusDay(int num, Date newDate) {
System.out.println("现在的日期是:" + newDate);
Calendar ca = Calendar.getInstance();
ca.setTime(newDate);
ca.add(Calendar.DATE, num);// num为增加的天数,可以改变的
newDate = ca.getTime();
System.out.println("增加天数以后的日期:" + newDate);
return newDate;
}
/**
* 当前日期加上天数后的日期
*
* @param num 为增加的天数
* @return
*/
public static Date plusDayByNum(int num) {
Date d = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currdate = format.format(d);
System.out.println("现在的日期是:" + currdate);
Calendar ca = Calendar.getInstance();
ca.add(Calendar.DATE, num);// num为增加的天数,可以改变的
d = ca.getTime();
// String enddate = format.format(d); //转化为字符串类型输出
// System.out.println("增加天数以后的日期:" + enddate);
System.out.println("增加天数以后的日期:" + d);
return d;
}
/* *
* @MethodName: wxTimeEnd
* @Description: 微信支付完成时间格式化
* @Param: [endTime]
* @Return: java.util.Date
* @Author: wyc
* @Date: 2020/8/26 10:21
**/
public static Date wxTimeEnd(String endTime) throws ParseException {
if (endTime == null || "".equals(endTime)) {
return new Date();
}
SimpleDateFormat format = new SimpleDateFormat(YYYYMMDDHHMMSS);
Date currdate = format.parse(endTime);
return currdate;
}
/**
* 去掉时分秒
*
* @param date
* @param pattern
* @return
*/
public static Date formatonversion(Date date, String pattern) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat(pattern);
String s = format.format(date);
date = format.parse(s);
return date;
}
/***
* 判断日期相差几个月 比较两个时间相差的月份
* @param start
* @param end
* @return
*/
public static int getMonth(Date start, Date end) {
if (start.after(end)) {
Date t = start;
start = end;
end = t;
}
Calendar startCalendar = Calendar.getInstance();
startCalendar.setTime(start);
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(end);
Calendar temp = Calendar.getInstance();
temp.setTime(end);
temp.add(Calendar.DATE, 1);
int year = endCalendar.get(Calendar.YEAR)
- startCalendar.get(Calendar.YEAR);
int month = endCalendar.get(Calendar.MONTH)
- startCalendar.get(Calendar.MONTH);
if ((startCalendar.get(Calendar.DATE) == 1)
&& (temp.get(Calendar.DATE) == 1)) {
return year * 12 + month + 1;
} else if ((startCalendar.get(Calendar.DATE) != 1)
&& (temp.get(Calendar.DATE) == 1)) {
return year * 12 + month;
} else if ((startCalendar.get(Calendar.DATE) == 1)
&& (temp.get(Calendar.DATE) != 1)) {
return year * 12 + month;
} else {
return (year * 12 + month - 1) < 0 ? 0 : (year * 12 + month);
}
}
/*
* 将时间转换为时间戳
*/
public static String dateToStamp(String s) throws ParseException {
String res;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = simpleDateFormat.parse(s);
long ts = date.getTime();
res = String.valueOf(ts);
return res;
}
/*
* 将时间戳转换为时间
*/
public static String stampToDate(String s) {
String res;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long lt = new Long(s);
Date date = new Date(lt);
res = simpleDateFormat.format(date);
return res;
}
public static Date stampTo1Date(String s) {
String res;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long lt = new Long(s);
Date date = new Date(lt);
// res = simpleDateFormat.format(date);
return date;
}
/**
* @Description:比较两个时间大小 1:now > validity ;2:now < validity
* @Author: wyc
* @Param:[now:当前时间或指定的时间, validity:待判定的时间]
* @return:int
* @methodName:compareDate
* @date:2021/6/17 9:04
*/
public static int compareDate(Date now, Date validity) {
if (validity != null) {
try {
if (now.getTime() > validity.getTime()) {
return 1;
} else if (now.getTime() < validity.getTime()) {
return 2;
} else {
return 0;
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
return 0;
}
/**
* 获得当天0点时间
*
* @return
*/
public static Date getTimesmorning() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
/**
* 获得昨天0点时间
*
* @return
*/
public static Date getYesterdaymorning() {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(getTimesmorning().getTime() - 3600 * 24 * 1000);
return cal.getTime();
}
/**
* 获得前天(两天 前)
*
* @return
*/
public static Date gettwoDaymorning() {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(getTimesmorning().getTime() - 3600 * 24 * 1000 * 2);
return cal.getTime();
}
/**
* 获得当天近3天时间
*
* @return
*/
public static Date getTriduumFromNow() {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(getTimesmorning().getTime() - 3600 * 24 * 1000 * 3);
return cal.getTime();
}
/**
* 获得当天近7天时间
*
* @return
*/
public static Date getWeekFromNow() {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(getTimesmorning().getTime() + 3600 * 24 * 1000 * 7);
return cal.getTime();
}
/**
* 获得七天前的
*
* @return
*/
public static Date getsevenDaymorning() {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(getTimesmorning().getTime() - 3600 * 24 * 1000 * 7);
return cal.getTime();
}
/**
* 获得当天近30天时间
*
* @return
*/
public static Date getThirtyDay() {
Calendar now = Calendar.getInstance();
now.add(Calendar.DAY_OF_MONTH, +30);
return now.getTime();
}
/**
* 获得当天近90天时间
*
* @return
*/
public static Date getNinetyDay() {
Calendar now = Calendar.getInstance();
now.add(Calendar.DAY_OF_MONTH, +90);
return now.getTime();
}
/**
* 获得当天24点时间
*
* @return
*/
public static Date getTimesnight() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 24);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
/**
* 获得本周一0点时间
*
* @return
*/
public static Date getTimesWeekmorning() {
Calendar cal = Calendar.getInstance();
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
return cal.getTime();
}
/**
* 获得本周日24点时间
*
* @return
*/
public static Date getTimesWeeknight() {
Calendar cal = Calendar.getInstance();
cal.setTime(getTimesWeekmorning());
cal.add(Calendar.DAY_OF_WEEK, 7);
return cal.getTime();
}
/**
* 获得本月第一天0点时间
*
* @return
*/
public static Date getTimesMonthmorning() {
Calendar cal = Calendar.getInstance();
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
return cal.getTime();
}
/**
* 获得本月最后一天24点时间
*
* @return
*/
public static Date getTimesMonthnight() {
Calendar cal = Calendar.getInstance();
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, 24);
return cal.getTime();
}
/**
* 上月初0点时间
*
* @return
*/
public static Date getLastMonthStartMorning() {
Calendar cal = Calendar.getInstance();
cal.setTime(getTimesMonthmorning());
cal.add(Calendar.MONTH, -1);
return cal.getTime();
}
/**
* 本季度开始点时间
*
* @return
*/
public static Date getCurrentQuarterStartTime() {
Calendar c = Calendar.getInstance();
int currentMonth = c.get(Calendar.MONTH) + 1;
SimpleDateFormat longSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd");
Date now = null;
try {
if (currentMonth >= 1 && currentMonth <= 3) {
c.set(Calendar.MONTH, 0);
} else if (currentMonth >= 4 && currentMonth <= 6) {
c.set(Calendar.MONTH, 3);
} else if (currentMonth >= 7 && currentMonth <= 9) {
c.set(Calendar.MONTH, 4);
} else if (currentMonth >= 10 && currentMonth <= 12) {
c.set(Calendar.MONTH, 9);
}
c.set(Calendar.DATE, 1);
now = longSdf.parse(shortSdf.format(c.getTime()) + " 00:00:00");
} catch (Exception e) {
e.printStackTrace();
}
return now;
}
/**
* 本季度结束点时间
*
* @return
*/
public static Date getCurrentQuarterEndTime() {
Calendar cal = Calendar.getInstance();
cal.setTime(getCurrentQuarterStartTime());
cal.add(Calendar.MONTH, 3);
return cal.getTime();
}
/**
* 本年開始点时间
*
* @return
*/
public static Date getCurrentYearStartTime() {
Calendar cal = Calendar.getInstance();
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.YEAR));
return cal.getTime();
}
/**
* 本年结束点时间
*
* @return
*/
public static Date getCurrentYearEndTime() {
Calendar cal = Calendar.getInstance();
cal.setTime(getCurrentYearStartTime());
cal.add(Calendar.YEAR, 1);
return cal.getTime();
}
/**
* 上年開始点时间
*
* @return
*/
public static Date getLastYearStartTime() {
Calendar cal = Calendar.getInstance();
cal.setTime(getCurrentYearStartTime());
cal.add(Calendar.YEAR, -1);
return cal.getTime();
}
/**
* @Description: 与当前时间相差几个月
* @Param:[date]
* @return:java.lang.Integer
* @methodName:monthCompare
* @date:2021/10/9 15:56
*/
public static Integer monthCompare(String dateStr) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date nowDate = new Date();
String nowDateStr = sdf.format(nowDate);
LocalDate from = LocalDate.parse(dateStr);
LocalDate to = LocalDate.parse(nowDateStr);
Integer months = Math.toIntExact(ChronoUnit.MONTHS.between(from, to));
System.out.println("months:" + months);
return months;
}
/**
* @Description: 获取”前一天“指定的时间点 比如获取10点数据 date=10即可
* @Param:[date]
* @return:java.util.Date
* @methodName:getEndTime
* @date:2021/10/19 17:48
*/
public static Date getStartTime(String date) {
Calendar time = Calendar.getInstance();
time.add(Calendar.DATE, -1);
time.set(Calendar.HOUR_OF_DAY, 22);
time.set(Calendar.MINUTE, 0);
time.set(Calendar.SECOND, 0);
time.set(Calendar.MILLISECOND, 0);
return time.getTime();
}
/**
* @Description: 获取当天指定的时间点 比如获取10点数据 date=10即可
* @Param:[date]
* @return:java.util.Date
* @methodName:getEndTime
* @date:2021/10/19 17:48
*/
public static Date getEndTime(String date) {
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, 10);
time.set(Calendar.MINUTE, 00);
time.set(Calendar.SECOND, 00);
time.set(Calendar.MILLISECOND, 999);
return time.getTime();
}
/**
* @Description: 获取”第二天“指定的时间点 比如获取10点数据 date=10即可
* @Param:[date]
* @return:java.util.Date
* @methodName:getEndTime
* @date:2021/10/19 17:48
*/
public static Date getNextDayEndTime(String date) {
Calendar time = Calendar.getInstance();
time.add(Calendar.DATE, 1);
time.set(Calendar.HOUR_OF_DAY, 22);
time.set(Calendar.MINUTE, 00);
time.set(Calendar.SECOND, 00);
time.set(Calendar.MILLISECOND, 999);
return time.getTime();
}
/**
* @Description: 毫秒时间转换为 时 分 秒
* @Param:[time]
* @return:java.lang.String
* @methodName:convertMillis
* @date:2021/10/20 9:30
*/
public static String convertMillis(long time) {
SimpleDateFormat sdf = new SimpleDateFormat("H'时':m'分':s'秒'");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(sdf.format(new Date(time)));
return sdf.format(new Date(time));
}
用的时间处理的方法。