一、功能概览
- 日期转换为指定格式的字符串;
- 日期字符串 → 日期(java.util.Date);
- 获取指定日期所在月份的天数;
- 时间戳转化为北京时间日期格式;
- 获取当前时间的时间戳,精确到秒。
- 时间戳 → 指定格式的字符串;
- 判断日期是否为月底最后一天;
- 计算两时间相距多少天;
- 取得新的日期;
- 比较两个时间大小(注意:两个日期中任意一个传入了NULL都会返回 0 );
- 得到两个时间差 格式yyyy-MM-dd HH:mm:ss;
- 获取当前日期是一个星期的第几天(注意:星期一为第一天,周日为最后一天);
- 判断指定时间是否在[startTime, endTime]区间(注意:时间格式要一致);
- 获取指定日期前后N个周期;
- 获取最近七天(之前的七天);
- 获取最近的一个月(之前的一个月);
- 获取月末最后一天;
- 日期范围 - 切片;
- 获得本周的最后一天,周日;
- 获得指定日期所在日的结束时间;
- 根据日期范围,得到按周期划分的日期区间值;
- 获取指定日期前后count天的集合;
二、完整源码
public class DateUtil {
private static final String yyyyMMddHHmmss = "yyyy-MM-dd HH:mm:ss";
private static final String yyyyMMdd = "yyyy-MM-dd";
private static final String HHmmdd = "HH:mm:ss";
private static final String DAY = "day", MONTH = "month", YEAR = "year", WEEK = "week";
private static final String HOUR = "hour", MINNUTE = "minute", SECOND = "second";
public static final String YEAR_REGEX = "^\\d{4}$";
public static final String MONTH_REGEX = "^\\d{4}(\\-|\\/|\\.)\\d{1,2}$";
public static final String DATE_REGEX = "^\\d{4}(\\-|\\/|\\.)\\d{1,2}\\1\\d{1,2}$";
public static String getDateTimeStr(Date date, String format) {
if (date == null) {
date = new Date();
}
if (format == null || format.isEmpty()) {
format = yyyyMMddHHmmss;
}
return new SimpleDateFormat(format).format(date);
}
public static Date getDateTime(String dateTimeStr, String format) {
if (format == null || format.isEmpty()) {
format = yyyyMMdd;
}
Date date = null;
try {
date = new SimpleDateFormat(format).parse(dateTimeStr);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
public static String getDaysOfMonth(String dateStr) {
return null;
}
public static String timestamp2DateTime(String pattern, long timestamp) {
SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.SIMPLIFIED_CHINESE);
return format.format(timestamp);
}
public static long getTimestamp() {
return System.currentTimeMillis() / 1000;
}
public static String getDateTime(String format, long timestamp) {
return new SimpleDateFormat(format).format(timestamp);
}
public static boolean isLastDayofMonth(Date date) {
Calendar calendar = Calendar.getInstance();
Calendar last = Calendar.getInstance();
calendar.setTime(date);
last.set(Calendar.DAY_OF_MONTH, last.getActualMaximum(Calendar.DAY_OF_MONTH));
String start = getDateTimeStr(date, yyyyMMdd);
String day = start.split("-")[2];
int days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
if (days == Integer.parseInt(day)) {
return true;
}
return false;
}
public static Integer calDateApart(String startDate, String endDate) {
startDate = startDate == null || startDate.isEmpty() ? getDateTimeStr(null, yyyyMMdd) : startDate;
endDate = endDate == null || endDate.isEmpty() ? getDateTimeStr(null, yyyyMMdd) : endDate;
DateFormat df = new SimpleDateFormat(yyyyMMdd);
Date d1 = new Date(), d2 = new Date();
try {
d1 = df.parse(startDate);
d2 = df.parse(endDate);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar start = Calendar.getInstance();
start.setTime(d1);
Long startTime = start.getTimeInMillis();
Calendar end = Calendar.getInstance();
end.setTime(d2);
Long endTime = end.getTimeInMillis();
Long oneDay = 1000 * 60 * 60 * 24l, days = (endTime - startTime) / oneDay;
int day = Integer.parseInt(String.valueOf(days));
return day;
}
public static Date addDays(Date date, long days) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, (int) days);
return cal.getTime();
}
public static int compareDay(Date date1, Date date2) {
if (date1 == null || date2 == null) {
return 0;
}
long a = date1.getTime(), b = date2.getTime();
return a < b ? 1 : (a > b ? -1 : 0);
}
public static boolean isBefore(Date date1, Date date2) {
long a = date1.getTime(), b = date2.getTime();
if (a < b) {
return true;
}
return false;
}
public static long dateSubtraction(String start, String end) {
SimpleDateFormat df = new SimpleDateFormat(yyyyMMddHHmmss);
try {
Date date1 = df.parse(start), date2 = df.parse(end);
return date2.getTime() - date1.getTime();
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
public static int getDayOfWeek(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal.get(Calendar.DAY_OF_WEEK) - 1;
}
public static boolean isEffectiveDate(Date nowTime, String dateSection) {
try {
String[] times = dateSection.split(",");
Date startTime = new SimpleDateFormat(yyyyMMdd).parse(times[0]);
Date endTime = new SimpleDateFormat(yyyyMMdd).parse(times[1]);
if (nowTime.getTime() == startTime.getTime()
|| nowTime.getTime() == endTime.getTime()) {
return true;
}
Calendar date = Calendar.getInstance();
date.setTime(nowTime);
Calendar begin = Calendar.getInstance();
begin.setTime(startTime);
Calendar end = Calendar.getInstance();
end.setTime(endTime);
if (isSameDay(date, begin) || isSameDay(date, end)) {
return true;
}
if (date.after(begin) && date.before(end)) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static boolean isSameDay(Calendar cal1, Calendar cal2) {
if (cal1 != null && cal2 != null) {
return cal1.get(0) == cal2.get(0) && cal1.get(1) == cal2.get(1) && cal1.get(6) == cal2.get(6);
} else {
throw new IllegalArgumentException("The date must not be null");
}
}
public static String getDatePeriod(Date date, String period, int count) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
if (YEAR.equals(period)) {
calendar.add(Calendar.YEAR, count);
} else if (MONTH.equals(period)) {
calendar.add(Calendar.MONTH, count);
} else if (WEEK.equals(period)) {
calendar.add(Calendar.WEEK_OF_MONTH, count);
} else {
calendar.add(Calendar.DAY_OF_MONTH, count);
}
date = calendar.getTime();
return new SimpleDateFormat(yyyyMMdd).format(date);
}
public static String getServen() {
SimpleDateFormat sdf = new SimpleDateFormat(yyyyMMdd);
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, -7);
Date monday = c.getTime();
String preMonday = sdf.format(monday);
return preMonday;
}
public static String getPreOneMonth() {
Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, -1);
return new SimpleDateFormat(yyyyMMdd).format(c.getTime());
}
private static String getMonthMaxDay(String sDate) {
Calendar cal = Calendar.getInstance();
Date date = null;
try {
date = new SimpleDateFormat(yyyyMMdd).parse(sDate + "-01");
} catch (ParseException e) {
e.printStackTrace();
}
cal.setTime(date);
int last = cal.getActualMaximum(Calendar.DATE);
return String.valueOf(last);
}
public static List<String> sliceUpDateRange(String startDate, String endDate) {
List<String> rs = new ArrayList<>();
try {
int dt = Calendar.DATE;
String pattern = "yyyy-MM-dd";
if (startDate.matches(YEAR_REGEX)) {
pattern = "yyyy";
dt = Calendar.YEAR;
} else if (startDate.matches(MONTH_REGEX)) {
pattern = "yyyy-MM";
dt = Calendar.MONTH;
} else if (startDate.matches(DATE_REGEX)) {
pattern = "yyyy-MM-dd";
dt = Calendar.DATE;
}
Calendar sc = Calendar.getInstance(), ec = Calendar.getInstance();
sc.setTime(getDateTime(startDate, pattern));
ec.setTime(getDateTime(endDate, pattern));
while (sc.compareTo(ec) < 1) {
rs.add(getDateTimeStr(sc.getTime(), pattern));
sc.add(dt, 1);
}
} catch (Exception e) {
e.printStackTrace();
}
return rs;
}
public static Date getCurrentWeekDayEndTime() {
Calendar c = Calendar.getInstance();
try {
int weekday = c.get(Calendar.DAY_OF_WEEK) - 1;
if (weekday == 0) {
weekday = 7;
}
c.add(Calendar.DATE, -weekday + 7);
c.setTime(new SimpleDateFormat().parse(new SimpleDateFormat().format(c.getTime()) + " 23:59:59"));
} catch (Exception e) {
e.printStackTrace();
}
return c.getTime();
}
public static Date getCurrentWeekDayStartTime() {
Calendar c = Calendar.getInstance();
try {
int weekday = c.get(Calendar.DAY_OF_WEEK) - 1;
if (weekday == 0) {
weekday = 7;
}
c.add(Calendar.DATE, -weekday + 1);
c.setTime(new SimpleDateFormat().parse(new SimpleDateFormat().format(c.getTime()) + " 00:00:00"));
} catch (Exception e) {
e.printStackTrace();
}
return c.getTime();
}
public static String getCurrentDayStartTime(Date date) {
String result = (date == null)
? new SimpleDateFormat(yyyyMMdd).format(System.currentTimeMillis())
: getDateTimeStr(date, yyyyMMdd);
return result.concat(" 00:00:00");
}
public static String getCurrentDayEndTime(Date date) {
String result = (date == null)
? new SimpleDateFormat(yyyyMMdd).format(System.currentTimeMillis())
: getDateTimeStr(date, yyyyMMdd);
return result.concat(" 23:59:59");
}
public static List<String> getPeriodDateList(String dateRange, String period) {
String startDate = dateRange.trim().split(",")[0], endDate = dateRange.trim().split(",")[1];
Date start = getDateTime(startDate, yyyyMMdd), end = getDateTime(endDate, yyyyMMdd);
List<String> result = new ArrayList<>();
if (DAY.equals(period)) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(start);
while (start.before(end) || start.equals(end)) {
result.add(new SimpleDateFormat(yyyyMMdd).format(calendar.getTimeInMillis()));
calendar.add(Calendar.DATE, 1);
start = calendar.getTime();
}
} else if (MONTH.equals(period)) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(start);
while (start.before(end) || start.equals(end)) {
result.add(new SimpleDateFormat("yyyy-MM").format(calendar.getTimeInMillis()));
calendar.add(Calendar.MONTH, 1);
start = calendar.getTime();
}
} else if (YEAR.equals(period)) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(start);
while (start.before(end) || start.equals(end)) {
result.add(new SimpleDateFormat("yyyy").format(calendar.getTimeInMillis()));
calendar.add(Calendar.YEAR, 1);
start = calendar.getTime();
}
}
return result;
}
public static List<String> getDayList(Date date, int count) {
List<String> result = new ArrayList<>();
Calendar c = Calendar.getInstance();
c.setTime(date);
boolean flag = false;
if (count < 0) {
count = Math.abs(count);
flag = true;
}
for (int i = 0; i < count; i++) {
result.add(new SimpleDateFormat(yyyyMMdd).format(c.getTimeInMillis()));
c.add(Calendar.DATE, flag ? -1 : 1);
}
if (flag){
Collections.reverse(result);
}
return result;
}
public static void main(String[] args) {
System.out.println(getDayList(new Date(), -7));
}
三、附录