直接看代码
package com.lsm.practice.date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtils {
public static Date getDate(String date, String pattern) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.parse(date);
}
public static Date getDate(Date date, String pattern) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.parse(sdf.format(date));
}
public static void main(String[] args) {
try {
isValidDate();
} catch (ParseException e) {
e.printStackTrace();
}
}
public static void isValidDate() throws ParseException {
String startDateStr = "20240101";
String endDateStr = "20240115";
String pattern = "yyyyMMdd";
Date startDate = getDate(startDateStr, pattern);
System.out.println("startDate=" + startDate);
Date endDate = getDate(endDateStr, pattern);
System.out.println("endDate=" + endDate);
Date nowDate = getDate("20240101", pattern);
System.out.println("nowDate=" + nowDate);
if (nowDate.after(startDate) && nowDate.before(endDate)) {
System.out.println("after和before,在目标时间区间内");
} else {
System.out.println("after和before,不在目标时间区间内");
}
if (nowDate.compareTo(startDate) >= 0 && nowDate.compareTo(endDate) <= 0) {
System.out.println("compareTo,在目标时间区间内");
} else {
System.out.println("compareTo,不在目标时间区间内");
}
}
public static void isValidTime() throws ParseException {
String startTime = "000000";
String endTime = "235959";
String pattern = "HHmmss";
Date startDate = getDate(startTime, pattern);
Date nowDate = getDate(new Date(), pattern);
System.out.println("nowDate=" + nowDate);
Date endDate = getDate(endTime, pattern);
System.out.println("endDate=" + endDate);
if (nowDate.after(startDate) && nowDate.before(endDate)) {
System.out.println("after和before,在目标时间区间内");
} else {
System.out.println("after和before,不在目标时间区间内");
}
if (nowDate.compareTo(startDate) >= 0 && nowDate.compareTo(endDate) <= 0) {
System.out.println("compareTo,在目标时间区间内");
} else {
System.out.println("compareTo,不在目标时间区间内");
}
}
public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
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);
return date.after(begin) && date.before(end);
}
}