最近在做一个项目,里面涉及到很多按照时间范围统计数据的需求,虽然MySQL自带的一些函数能够获取特定的时间范围,但一方面sql写起来很比较复杂,而且总归不能满足全部需求。因此本人整理了一个日期的工具类,便于快速得到指定时间范围的开始时间和结束时间,sql查询时只要传入两个时间戳即可,简单直接。废话不多说,直接上代码
package com.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
/**
* @author oy
* @date 2022/9/13 10:16
*/
public class DateUtil {
/**
* 获取今天开始时间和结束时间
*
* @return Map
*/
public static Map<String, String> getTodayTime() {
Long startTime = getStartTime();
//当期时间
//Long endTime = getEndTime();
long endTime = System.currentTimeMillis();
return getMapByStartEndTime(startTime, endTime);
}
/**
* 获取指定date今天开始时间和结束时间
*
* @return Map
*/
public static Map<String, String> getTodayTime(Date date) {
Long startTime = getStartTime();
//当期时间
//Long endTime = getEndTime();
long endTime = date.getTime();
return getMapByStartEndTime(startTime, endTime);
}
/**
* 获取今天日期 年月日
*
* @return Date
*/
public static Date getTodayYmd() {
Date now = new Date();
Calendar cal1 = Calendar.getInstance();
cal1.setTime(now);
//将时分秒,毫秒域清零
cal1.set(Calendar.HOUR_OF_DAY, 0);
cal1.set(Calendar.MINUTE, 0);
cal1.set(Calendar.SECOND, 0);
cal1.set(Calendar.MILLISECOND, 0);
return cal1.getTime();
}
//获取昨天日期 年月日
public static Date getYesterdayYmd() {
Calendar cal = new GregorianCalendar();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.DAY_OF_MONTH, -1);
return cal.getTime();
}
/**
* 获取昨天开始时间和结束时间
*
* @return Map<String, String>
*/
public static Map<String, String> getYesterdayTime() {
Long startTime = getBeginDayOfYesterday();
Long endTime = getEndDayOfYesterDay();
return getMapByStartEndTime(startTime, endTime);
}
/**
* 获取当月开始时间和结束时间
*
* @return Map<String, String>
*/
public static Map<String, String> getMonthTime() {
Long startTime = getMonthStartTime();
Long endTime = getMonthEndTime();
return getMapByStartEndTime(startTime, endTime);
}
/**
*
* 获取指定日期当月开始时间和结束时间
*
* @return Map<String, String>
*/
public static Map<String, String> getMonthTime(Date date) {
Long startTime = getMonthStartTime();
Long endTime = getMonthEndTime();
return getMapByStartEndTime(startTime, endTime);
}
/**
* 获取上个月月开始时间和结束时间
*
* @return Map<String, String>
*/
public static Map<String, String> getLastMonthTime() {
Long startTime = getLastMonthStartTime();
Long endTime = getLastMonthEndTime();
return getMapByStartEndTime(startTime, endTime);
}
/**
* 根据指定date获取上个月月开始时间和结束时间
*
* @return Map<String, String>
*/
public static Map<String, String> getLastMonthTime(Date date) throws Exception {
Long startTime = getLastMonthStartTime(date);
Long endTime = getLastMonthEndTime(date);
DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String startTimeStr = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(startTime), ZoneId.systemDefault()));
String endTimeStr = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(endTime), ZoneId.systemDefault()));
Map<String, String> map = new HashMap<>(2);
map.put("startDate", startTimeStr);
map.put("endDate", endTimeStr);
return map;
}
/**
* 获取月均开始和结束时间
*
* @param minCreateTime
* @return
* @throws ParseException
*/
public static Map<String, Object> getAverageTime(String minCreateTime) throws ParseException {
Long yesterdayTimeEnd = getEndDayOfYesterDay();
DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//昨天的时间
String yesterdayStr = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(yesterdayTimeEnd), ZoneId.systemDefault()));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String yesterdayBefore30Str;
Calendar calc = Calendar.getInstance();
calc.setTime(sdf.parse(yesterdayStr));
calc.add(Calendar.DATE, -30);
calc.set(Calendar.HOUR_OF_DAY, 0);
calc.set(Calendar.MINUTE, 0);
calc.set(Calendar.SECOND, 0);
calc.set(Calendar.MILLISECOND, 0);
Date minDate = calc.getTime();
yesterdayBefore30Str = sdf.format(minDate);
int num = daysBetween(yesterdayBefore30Str, yesterdayStr);
int checkNum = daysBetween(minCreateTime, yesterdayBefore30Str);
System.out.println("checkNum:" + checkNum);
Map<String, Object> map = new HashMap<>(16);
if (checkNum < 0) {
int numNew = daysBetween(minCreateTime, yesterdayStr);
map.put("startDate", minCreateTime);
map.put("endDate", yesterdayStr);
//取绝对值
map.put("num", Math.abs(numNew));
return map;
}
map.put("startDate", yesterdayBefore30Str);
map.put("endDate", yesterdayStr);
map.put("num", num);
return map;
}
public static int daysBetween(String smdate, String bdate) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.setTime(sdf.parse(smdate));
long time1 = cal.getTimeInMillis();
cal.setTime(sdf.parse(bdate));
long time2 = cal.getTimeInMillis();
long between_days = (time2 - time1) / (1000 * 3600 * 24);
return Integer.parseInt(String.valueOf(between_days));
}
/**
* 获取今天开始时间
*/
private static Long getStartTime() {
Calendar todayStart = Calendar.getInstance();
todayStart.set(Calendar.HOUR_OF_DAY, 0);
todayStart.set(Calendar.MINUTE, 0);
todayStart.set(Calendar.SECOND, 0);
todayStart.set(Calendar.MILLISECOND, 0);
return todayStart.getTimeInMillis();
}
/**
* 获取今天结束时间
*/
private static Long getEndTime() {
Calendar todayEnd = Calendar.getInstance();
todayEnd.set(Calendar.HOUR, 23);
todayEnd.set(Calendar.MINUTE, 59);
todayEnd.set(Calendar.SECOND, 59);
todayEnd.set(Calendar.MILLISECOND, 999);
return todayEnd.getTime().getTime();
}
/**
* 获取当月开始时间
*/
public static Long getMonthStartTime() {
Long currentTime = System.currentTimeMillis();
String timeZone = "GMT+8:00";
//获取当前日期
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone(timeZone));
calendar.setTimeInMillis(currentTime);
calendar.add(Calendar.YEAR, 0);
calendar.add(Calendar.MONTH, 0);
//设置为1号,当前日期既为本月第一天
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTimeInMillis();
}
/**
* 获取当月的结束时间戳
*/
public static Long getMonthEndTime() {
Long currentTime = System.currentTimeMillis();
String timeZone = "GMT+8:00";
Calendar calendar = Calendar.getInstance();// 获取当前日期
calendar.setTimeZone(TimeZone.getTimeZone(timeZone));
calendar.setTimeInMillis(currentTime);
calendar.add(Calendar.YEAR, 0);
calendar.add(Calendar.MONTH, 0);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));// 获取当前月最后一天
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return calendar.getTimeInMillis();
}
/**
* 获取指定date30天前的时间
* @param date
* @return
*/
public static String get30DayBefore(Date date) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c = Calendar.getInstance();
//过去七天
c.setTime(date);
c.add(Calendar.DATE, - 7);
Date d = c.getTime();
String day = format.format(d);
System.out.println("过去七天:"+day);
//过去一月
c.setTime(new Date());
c.add(Calendar.MONTH, -1);
Date m = c.getTime();
String mon = format.format(m);
System.out.println("过去一个月:"+mon);
return mon;
}
public static Long getLastMonthStartTime() {
long currentTime = System.currentTimeMillis();
return getLastMonthStartTime(currentTime);
}
private static Long getLastMonthStartTime(Date date) {
long time = date.getTime();
return getLastMonthStartTime(time);
}
private static Long getLastMonthStartTime(long time) {
String timeZone = "GMT+8:00";
Calendar calendar = Calendar.getInstance();// 获取当前日期
calendar.setTimeZone(TimeZone.getTimeZone(timeZone));
calendar.setTimeInMillis(time);
calendar.add(Calendar.YEAR, 0);
calendar.add(Calendar.MONTH, -1);
// 设置为1号,当前日期既为本月第一天
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTimeInMillis();
}
public static Long getLastMonthEndTime() {
long currentTime = System.currentTimeMillis();
return getLastMonthEndTime(currentTime);
}
private static Long getLastMonthEndTime(Date date) {
long time = date.getTime();
return getLastMonthEndTime(time);
}
private static Long getLastMonthEndTime(long time) {
String timeZone = "GMT+8:00";
// 获取当前日期
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone(timeZone));
calendar.setTimeInMillis(time);
calendar.add(Calendar.YEAR, 0);
calendar.add(Calendar.MONTH, -1);
// 获取当前月最后一天
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return calendar.getTimeInMillis();
}
public static Long getBeginDayOfYesterday() {
Calendar cal = new GregorianCalendar();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.DAY_OF_MONTH, -1);
return cal.getTimeInMillis();
}
public static Long getEndDayOfYesterDay() {
Calendar cal = new GregorianCalendar();
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.add(Calendar.DAY_OF_MONTH, -1);
return cal.getTimeInMillis();
}
/**
* 获取今年是哪一年
*
* @return
*/
public static Integer getNowYear() {
Date date = new Date();
GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
gc.setTime(date);
return gc.get(1);
}
public static Map<String, String> getThisYearTime() throws Exception {
Long startTime = getBeginDayOfYear();
Long endTime = getEndDayOfYear();
DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String startTimeStr = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(startTime), ZoneId.systemDefault()));
String endTimeStr = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(endTime), ZoneId.systemDefault()));
Map<String, String> map = new HashMap<>();
map.put("startDate", startTimeStr);
map.put("endDate", endTimeStr);
return map;
}
/**
* 获取本年的开始时间
*
* @return
*/
public static Long getBeginDayOfYear() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, getNowYear());
// cal.set
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.DATE, 1);
return getDayStartTime(cal.getTime());
}
/**
* 获取本年的结束时间
*
* @return
*/
public static Long getEndDayOfYear() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, getNowYear());
cal.set(Calendar.MONTH, Calendar.DECEMBER);
cal.set(Calendar.DATE, 31);
return getDayEndTime(cal.getTime());
}
/**
* 获取某个日期的开始时间
*
* @param d
* @return
*/
public static Long 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 calendar.getTimeInMillis();
}
/**
* 获取某个日期的结束时间
*
* @param d
* @return
*/
public static Long 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 calendar.getTimeInMillis();
}
/**
* 获取本周的第一天
*
* @return String
**/
public static String getWeekStart(Date date) {
Calendar cal = Calendar.getInstance();
if (null != date) {
cal.setTime(date);
}
cal.add(Calendar.WEEK_OF_MONTH, 0);
cal.set(Calendar.DAY_OF_WEEK, 2);
Date time = cal.getTime();
return new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(time);
}
/**
* 获取本周的最后一天
*
* @return String
**/
public static String getWeekEnd(Date date) {
Calendar cal = Calendar.getInstance();
if (null != date) {
cal.setTime(date);
}
cal.set(Calendar.DAY_OF_WEEK, cal.getActualMaximum(Calendar.DAY_OF_WEEK));
cal.add(Calendar.DAY_OF_WEEK, 1);
Date time = cal.getTime();
return new SimpleDateFormat("yyyy-MM-dd 23:59:59").format(time);
}
/**
* 根据日期取得一周的第几天
*
* @param date date
* @return String
*/
public static int getWeekIndex(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int weekIndex = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (weekIndex < 0) {
return 0;
} else if (weekIndex == 0) {
return 7;
} else {
return weekIndex;
}
}
/**
* 根据日期取得星期几
*
* @param date date
* @return String
*/
public static String getWeek(Date date) {
String[] weeks = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (week_index < 0) {
week_index = 0;
}
return weeks[week_index];
}
private static Map<String, String> getMapByStartEndTime(Long startTime, long endTime) {
DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String startTimeStr = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(startTime), ZoneId.systemDefault()));
String endTimeStr = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(endTime), ZoneId.systemDefault()));
Map<String, String> map = new HashMap<>();
map.put("startDate", startTimeStr);
map.put("endDate", endTimeStr);
return map;
}
public static void main(String[] args) throws Exception {
Map<String, String> todayTime = getTodayTime(new Date());
System.out.println("今天:" + todayTime);
Map<String, String> yesterdayTime = getYesterdayTime();
System.out.println("昨天:" + yesterdayTime);
Map<String, String> monthTime = getMonthTime();
System.out.println("当月:" + monthTime);
Map<String, String> lastMonthTime = getLastMonthTime();
System.out.println("上个月:" + lastMonthTime);
long curTime = System.currentTimeMillis();
Date curDate = new Date(curTime);
int weekIndex = getWeekIndex(curDate);
System.out.println("week index : " + weekIndex);
String weekStart = getWeekStart(curDate);
String weekEnd = getWeekEnd(curDate);
System.out.println("week start:" + weekStart + ", week end: " + weekEnd);
Map<String, String> monthTimeMap = getMonthTime();
System.out.println("当月:" + monthTimeMap);
}
}