如何用JAVA判斷當(dāng)前時(shí)間是否為節(jié)假日、周末、工作日及調(diào)休日(不報(bào)錯(cuò):IOException!)
需求
有這么個(gè)需求,需要判斷傳的這個(gè)日期是否為節(jié)假日,周末,工作日,然后做剩下的操作。
話不多說(shuō),上代碼
1.首先需要拿到節(jié)假日api
- 其實(shí)這個(gè)api里有接口可以直接判斷某天是否為周末,節(jié)假日,工作日;
- 但是這個(gè)接口訪問(wèn)多了會(huì)報(bào)一個(gè)403的錯(cuò)誤,也就是請(qǐng)求太多導(dǎo)致的;
- 而我下面的內(nèi)容是只請(qǐng)求一次全年節(jié)假日即可,放到一個(gè)集合里,第二次請(qǐng)求判斷的時(shí)候就可以直接去集合里判斷。速度很快!
2.拿到自己適用接口,如下:
參數(shù):
1》year:格式“yyyy”,查詢這一年的節(jié)假日
https://timor.tech/api/holiday/year
返回?cái)?shù)據(jù)示例:
{
"code": 0,
"holiday": {
"01-01": {
"holiday": true,
"name": "元旦",
"wage": 3,
"date": "2023-01-01",
"rest": 1
},
"01-02": {
"holiday": true,
"name": "元旦",
"wage": 2,
"date": "2023-01-02",
"rest": 1
},
"01-21": {
"holiday": true,
"name": "除夕",
"wage": 3,
"date": "2023-01-21",
"rest": 2
},
..........
截圖如下

3.拿到項(xiàng)目中,編寫(xiě)成一個(gè)HolidayUtil 工具類,代碼如下:
/**
* 判斷今天是工作日/周末/節(jié)假日 工具類
* //0 上班 1周末 2節(jié)假日
*/
public class HolidayUtil {
static Map<String,List<String>> holiday =new HashMap<>();//假期
static Map<String,List<String>> extraWorkDay =new HashMap<>();//調(diào)休日
//判斷是否為節(jié)假日
/**
*
* @param time 日期參數(shù) 格式‘yyyy-MM-dd',不傳參則默認(rèn)當(dāng)前日期
* @return
*/
public static String isWorkingDay(String time) throws ParseException {
Date parse = null;
//為空則返回當(dāng)前時(shí)間
if (StringUtils.isNotBlank(time)){
SimpleDateFormat getYearFormat = new SimpleDateFormat("yyyy-MM-dd");
parse = getYearFormat.parse(time);
}else {
parse = new Date();
}
String newDate = new SimpleDateFormat("yyyy").format(parse);
//判斷key是否有參數(shù)年份
if(!holiday.containsKey(newDate)){
String holiday = getYearHoliday(newDate);
if ("No!".equals(holiday)){
return "該年份未分配日期安排!";
}
}
//得到日期是星期幾
Date date = DateUtil.formatStringToDate(time, false);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int weekday = DateUtil.getDayOfWeek(calendar);
//是否節(jié)假日
if(holiday.get(newDate).contains(time)){
return "2";
}else if(extraWorkDay.get(newDate).contains(time)){//是否為調(diào)休
return "0";
}else if(weekday == Calendar.SATURDAY || weekday == Calendar.FRIDAY){//是否為周末
return "1";
}else{
return "0";
}
}
/**
*
* @param date 日期參數(shù) 格式‘yyyy',不傳參則默認(rèn)當(dāng)前日期
* @return
*/
public static String getYearHoliday(String date) throws ParseException {
//獲取免費(fèi)api地址
String httpUrl="https://timor.tech/api/holiday/year/"+date;
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
try {
URL url = new URL(httpUrl);
URLConnection connection = url.openConnection();
//connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
connection.setRequestProperty("User-Agent", "Mozilla/4.76");
//使用Get方式請(qǐng)求數(shù)據(jù)
//connection.setRequestMethod("GET");
//connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
//字符串轉(zhuǎn)json
JSONObject json = JSON.parseObject(sbf.toString());
//根據(jù)holiday字段獲取jsonObject內(nèi)容
JSONObject holiday = json.getJSONObject("holiday");
if (holiday.size() == 0){
return "No!";
}
List hoList = new ArrayList<>();
List extraList = new ArrayList<>();
for (Map.Entry<String, Object> entry : holiday.entrySet()) {
String value = entry.getValue().toString();
JSONObject jsonObject = JSONObject.parseObject(value);
String hoBool = jsonObject.getString("holiday");
String extra = jsonObject.getString("date");
//判斷不是假期后調(diào)休的班
if(hoBool.equals("true")){
hoList.add(extra);
HolidayUtil.holiday.put(date,hoList);
}else {
extraList.add(extra);
HolidayUtil.extraWorkDay.put(date,extraList);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
DateUtil工具類,這里寫(xiě)了很多,可以把不需要的刪除掉
/**
* 日期工具
*/
public class DateUtil {
/**
* 輸出當(dāng)天的時(shí)間,格式如:20151207
*
* @return
*/
public static String today() {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
return format.format(new Date());
}
/**
* 當(dāng)前時(shí)間
* @return
*/
public static String currTime() {
SimpleDateFormat sdfDetail = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
return sdfDetail.format(date);
}
/**
* 當(dāng)前年
* @return
*/
public static String currYear() {
SimpleDateFormat sdfDetail = new SimpleDateFormat("yyyy");
Date date = new Date();
return sdfDetail.format(date);
}
public static String format(Date date, String tpl) {
SimpleDateFormat format = new SimpleDateFormat(tpl);
return format.format(date);
}
/**
* 任意一天的開(kāi)始時(shí)間
*
* @return date
*/
public static Date startOfDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Date returnDate = calendar.getTime();
return returnDate;
}
/**
* 任意一天的結(jié)束時(shí)間
*
* @return date
*/
public static Date endOfDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
Date returnDate = calendar.getTime();
return returnDate;
}
/**
* 獲取時(shí)間戳的開(kāi)始時(shí)間
* @param timestamp
*/
public static Long startOfDayByTimestamp(Long timestamp) {
Date date = new Date(timestamp);
return startOfDay(date).getTime();
}
/**
* 獲取時(shí)間戳的結(jié)束時(shí)間
* zg
* @param timestamp
*/
public static Long endOfDayByTimestamp(Long timestamp) {
Date date = new Date(timestamp);
return endOfDay(date).getTime();
}
/**
* 當(dāng)天的開(kāi)始時(shí)間
*
* @return
*/
public static Date startOfTodDay() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Date date = calendar.getTime();
return date;
}
/**
* 當(dāng)天的結(jié)束時(shí)間
*
* @return
*/
public static Date endOfTodDay() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
Date date = calendar.getTime();
return date;
}
/**
* 昨天的開(kāi)始時(shí)間
*
* @return
*/
public static Date startOfyesterday() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.add(Calendar.DATE, -1);
calendar.set(Calendar.MILLISECOND, 0);
Date date = calendar.getTime();
return date;
}
/**
* 昨天的結(jié)束時(shí)間
*
* @return
*/
public static Date endOfyesterday() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
calendar.add(Calendar.DATE, -1);
Date date = calendar.getTime();
return date;
}
/**
* 功能:獲取本周的開(kāi)始時(shí)間 示例:2013-05-13 00:00:00
*/
public static Date startOfThisWeek() {// 當(dāng)周開(kāi)始時(shí)間
Calendar currentDate = Calendar.getInstance();
currentDate.setFirstDayOfWeek(Calendar.MONDAY);
currentDate.set(Calendar.HOUR_OF_DAY, 0);
currentDate.set(Calendar.MINUTE, 0);
currentDate.set(Calendar.SECOND, 0);
currentDate.set(Calendar.MILLISECOND, 0);
currentDate.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
Date date = currentDate.getTime();
return date;
}
/**
* 功能:獲取String日期對(duì)應(yīng)的時(shí)間戳
* format 格式自定
*
* @return
*/
public static Long formatStringToStamp(String base, String format) {
DateFormat df = new SimpleDateFormat(format);
Date baseTime;
Long stamp = null;
try {
baseTime = df.parse(base);
stamp = baseTime.getTime();
} catch (Exception e) {
return null;
}
return stamp;
}
/**
* 功能:獲取String日期對(duì)應(yīng)的時(shí)間
* isTotal = false ;yyyy-MM-dd格式限定
* isTotal = true ;yyyy-MM-dd hh-mm-ss格式限定
*/
public static Date formatStringToDate(String base, Boolean isTotal) {
String format = isTotal ? "yyyy-MM-dd hh-mm-ss" : "yyyy-MM-dd";
DateFormat df = new SimpleDateFormat(format);
Date baseTime;
try {
baseTime = df.parse(base);
} catch (Exception e) {
return null;
}
return baseTime;
}
/**
* 功能:獲取本周的結(jié)束時(shí)間 示例:2013-05-19 23:59:59
*/
public static Date endOfThisWeek() {// 當(dāng)周結(jié)束時(shí)間
Calendar currentDate = Calendar.getInstance();
currentDate.setFirstDayOfWeek(Calendar.MONDAY);
currentDate.set(Calendar.HOUR_OF_DAY, 23);
currentDate.set(Calendar.MINUTE, 59);
currentDate.set(Calendar.SECOND, 59);
currentDate.set(Calendar.MILLISECOND, 999);
currentDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
Date date = currentDate.getTime();
return date;
}
/**
* 功能:獲取本月的開(kāi)始時(shí)間
*/
public static Date startOfThisMonth() {// 當(dāng)周開(kāi)始時(shí)間
Calendar currentDate = Calendar.getInstance();
currentDate.set(Calendar.HOUR_OF_DAY, 0);
currentDate.set(Calendar.MINUTE, 0);
currentDate.set(Calendar.SECOND, 0);
currentDate.set(Calendar.MILLISECOND, 0);
currentDate.set(Calendar.DAY_OF_MONTH, 1);
Date date = currentDate.getTime();
return date;
}
public static Date endOfThisMonth() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 999);
cal.add(Calendar.MONTH, 1);
cal.add(Calendar.DATE, -1);
Date date = cal.getTime();
return date;
}
/**
* 功能:獲取上月的開(kāi)始時(shí)間
*/
public static Date startOfLastMonth() {// 當(dāng)周開(kāi)始時(shí)間
Calendar currentDate = Calendar.getInstance();
currentDate.set(Calendar.HOUR_OF_DAY, 0);
currentDate.set(Calendar.MINUTE, 0);
currentDate.set(Calendar.SECOND, 0);
currentDate.set(Calendar.MILLISECOND, 0);
currentDate.set(Calendar.DAY_OF_MONTH, 1);
currentDate.add(Calendar.MONTH, -1);
Date date = currentDate.getTime();
return date;
}
/**
* 功能:獲取上月的結(jié)束時(shí)間
*/
public static Date endOfLastMonth() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 999);
cal.add(Calendar.DATE, -1);
Date date = cal.getTime();
return date;
}
private static final int[] DAY_OF_MONTH = new int[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
public static final String[] DATE_FORMATS = new String[]{"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd",
"yyyy-MM", "yyyy-MM-dd HH:mm:ss.S", "yyyy年MM月dd日", "yyyy年MM月dd日 HH:mm", "yyyyMMdd", "yyyy年MM月dd日 HH:mm:ss",
"MM.dd"};
/**
* 將傳入的日期轉(zhuǎn)化為"yyyy-MM-dd"形式的字符串
*
* @param dt 日期
* @return 指定日期格式的字符串
*/
public static String formatDate(Date dt) {
return formatDate("yyyy-MM-dd", dt);
}
/**
* 將傳入的日期轉(zhuǎn)化為"yyyy-MM-dd HH:mm:ss"形式的字符串
*
* @param dt 日期
* @return 指定日期格式的字符串
*/
public static String formatDateYMDHMS(Date dt) {
return formatDate("yyyy-MM-dd HH:mm:ss", dt);
}
/**
* 將傳入的日期轉(zhuǎn)化為"yyyy-MM-dd HH:mm"形式的字符串
*
* @param dt 日期
* @return 指定日期格式的字符串
*/
public static String formatDateYMDHM(Date dt) {
return formatDate("yyyy-MM-dd HH:mm", dt);
}
/**
* 將傳入的日期以指定格式轉(zhuǎn)成字符串
*
* @param format
* @param dt
* @return
*/
public static String formatDate(String format, Date dt) {
if (dt == null) {
return "";
}
if (format.isEmpty()) {
format = "yyyy-MM-dd";
}
SimpleDateFormat fmt = new SimpleDateFormat(format);
return fmt.format(dt);
}
/**
* 將日期字符串轉(zhuǎn)為日期
*
* @param dateStr 日期字符串
* @return
*/
public static Date parseDate(String dateStr) {
return parseDate(dateStr, DATE_FORMATS);
}
/**
* 將日期字符串轉(zhuǎn)為指定格式的日期
*
* @param dateStr 日期字符串
* @param format 日期格式
* @return
*/
public static Date parseDate(String dateStr, String format) {
return parseDate(dateStr, new String[]{format});
}
private static Date parseDate(String dateStr, String[] parsePatterns) {
try {
return DateUtils.parseDate(dateStr, parsePatterns);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* 獲取今天的日期
*
* @return
*/
public static Date getToday() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
/**
* 得到傳入日期n天后的日期,如果傳入日期為null,則表示當(dāng)前日期n天后的日期
*
* @param dt 日期
* @param days 可以為任何整數(shù),負(fù)數(shù)表示前days天,正數(shù)表示后days天
* @return Date
*/
public static Date getAddDayDate(Date dt, int days) {
Calendar cal = Calendar.getInstance();
if (dt != null) {
cal.setTime(dt);
}
cal.add(Calendar.DAY_OF_MONTH, days);
return cal.getTime();
}
/**
* 得到當(dāng)前日期幾天后(plusDays>0)or 幾天前(plusDays<0)的指定格式的字符串日期
*
* @param dt
* @param plusDays
* @param dateFormat
* @return
*/
public static String getAddDayDateFromToday(int plusDays, String dateFormat) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, plusDays);
return formatDate(dateFormat, cal.getTime());
}
/**
* 給定的時(shí)間再加上指定小時(shí)數(shù),如果傳入日期為null,能以當(dāng)前時(shí)間計(jì)算
*
* @param dt
* @param hours
* @return
* @author Alex Zhang
*/
public static Date getAddHourDate(Date dt, int hours) {
if (dt == null)
dt = new Date(System.currentTimeMillis());
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
cal.add(Calendar.HOUR, hours);
return cal.getTime();
}
/**
* 給定的時(shí)間再加上指定分鐘數(shù)
*
* @param dt
* @param minutes
* @return
*/
public static Date getAddMinuteDate(Date dt, int minutes) {
if (dt == null)
dt = new Date(System.currentTimeMillis());
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
cal.add(Calendar.MINUTE, minutes);
return cal.getTime();
}
/**
* 給定的時(shí)間再加上指定月份數(shù)
*
* @param dt
* @param months
* @return
*/
public static Date getAddMonthDate(Date dt, int months) {
if (dt == null)
dt = new Date(System.currentTimeMillis());
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
cal.add(Calendar.MONTH, months);
return cal.getTime();
}
/**
* 給定的時(shí)間再加上指定年
* @param dt
* @param year
* @return
*/
public static Date getAddYearDate(Date dt, int year) {
if (dt == null)
dt = new Date(System.currentTimeMillis());
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
cal.add(Calendar.YEAR, year);
return cal.getTime();
}
/**
* 獲得某天的零點(diǎn)時(shí)刻0:0:0
*
* @param date 日期
* @return
*/
public static Date getDayBegin(Date date) {
if (date == null)
return null;
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
/**
* 獲得某天的截至?xí)r刻23:59:59
*
* @param date
* @return
*/
public static Date getDayEnd(Date date) {
if (date == null)
return null;
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 999);
return cal.getTime();
}
/**
* 某月的起始時(shí)間,eg:param:2011-11-10 12:10:50.999, return:2011-11-1 00:00:00.000
*/
public static Date getMonthBeginTime(Date dt) {
if (dt == null)
dt = new Date(System.currentTimeMillis());
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
/**
* 某月的截止時(shí)間,eg:param:2011-11-10 12:10:50.999, return:2011-11-30 23:59:59.999
*/
public static Date getMonthEndTime(Date dt) {
if (dt == null)
dt = new Date(System.currentTimeMillis());
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) + 1);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, -1);
return cal.getTime();
}
/**
* 獲得傳入日期的年\月\日,以整型數(shù)組方式返回
*
* @param dt
* @return int[]
*/
public static int[] getTimeArray(Date dt) {
if (dt == null)
dt = new Date(System.currentTimeMillis());
int[] timeArray = new int[3];
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
timeArray[0] = cal.get(Calendar.YEAR);
timeArray[1] = cal.get(Calendar.MONTH) + 1;
timeArray[2] = cal.get(Calendar.DAY_OF_MONTH);
return timeArray;
}
/**
* 獲得傳入日期的年\月\日\(chéng)小時(shí)\分,以整型數(shù)組方式返回
*
* @param dt
* @return
*/
public static int[] timeArray(Date dt) {
if (dt == null)
dt = new Date(System.currentTimeMillis());
int[] timeArray = new int[5];
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
timeArray[0] = cal.get(Calendar.YEAR);
timeArray[1] = cal.get(Calendar.MONTH) + 1;
timeArray[2] = cal.get(Calendar.DAY_OF_MONTH);
timeArray[3] = cal.get(Calendar.HOUR_OF_DAY);
timeArray[4] = cal.get(Calendar.MINUTE);
return timeArray;
}
/**
* 根據(jù)年月日得到Date類型時(shí)間
*
* @param year
* @param month
* @param day
* @return Date
*/
public static Date getTime(Integer year, Integer month, Integer day) {
Calendar cal = Calendar.getInstance();
if (year != null)
cal.set(Calendar.YEAR, year);
if (month != null)
cal.set(Calendar.MONTH, month - 1);
if (day != null)
cal.set(Calendar.DAY_OF_MONTH, day);
return cal.getTime();
}
/**
* @param parrern 格式化字符串 例如:yyyy-MM-dd
* @param str 時(shí)間字符串 例如:2007-08-01
* @return 出錯(cuò)返回null
* 通過(guò)格式化字符串得到時(shí)間
*/
public static Date getDateFromPattern(String parrern, String str) {
SimpleDateFormat fmt = new SimpleDateFormat(parrern);
try {
return fmt.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
* 計(jì)算兩個(gè)日期間相隔的小時(shí)
*
* @param d1 日期1
* @param d2 日期2
* @return
*/
public static int getHourBetween(Date d1, Date d2) {
long m = d1.getTime();
long n = d2.getTime();
return (int) ((m - n) / 3600000);
}
/**
* 取得兩個(gè)時(shí)間之間的天數(shù),可能是負(fù)數(shù)(第二個(gè)時(shí)間的日期小于第一個(gè)時(shí)間的日期)。如果兩個(gè)時(shí)間在同一天,則返回0
*
* @param d1 第一個(gè)時(shí)間
* @param d2 第二個(gè)時(shí)間
* @return
* @author Derek
* @version 1.0 2009-10-14
*/
public static int getDayBetween(Date d1, Date d2) {
Calendar c1 = Calendar.getInstance();
c1.setTime(d1);
Calendar c2 = Calendar.getInstance();
c2.setTime(d2);
return (int) ((c2.getTimeInMillis() - c1.getTimeInMillis()) / 86400000);
}
/**
* 計(jì)算兩個(gè)日期間相隔的秒數(shù)
*
* @param d1 日期1
* @param d2 日期2
* @return
*/
public static long getSecondBetweem(Date d1, Date d2) {
return (d1.getTime() - d2.getTime()) / 1000;
}
/**
* 計(jì)算兩個(gè)日期間相隔的月份數(shù)
*
* @param d1 日期1
* @param d2 日期2
* @return
*/
public static int getMonthBetween(Date d1, Date d2) {
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(d1);
c2.setTime(d2);
return (c1.get(Calendar.YEAR) - c2.get(Calendar.YEAR)) * 12 + (c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH));
}
/**
* 通過(guò)生日得到當(dāng)前年齡
*
* @param birthDay 以字符串表示的生日
* @return 返回以以字符串表示的年齡, 最小為0
*/
public static String getAge(String birthDay) {
if (birthDay.startsWith("0000")) {
return "未知";
}
if (!birthDay.matches("[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}")) {
return "未知";
}
return getAge(parseDate(birthDay, "yyyy-MM-dd"));
}
/**
* 通過(guò)生日得到當(dāng)前年齡
*
* @param birthDate 以日期表示的生日
* @return 返回以以字符串表示的年齡, 最小為0
*/
public static String getAge(Date birthDate) {
if (birthDate == null) {
return "未知";
}
Calendar cal = Calendar.getInstance();
if (cal.before(birthDate)) {
throw new IllegalArgumentException("The birthDay is before Now. It is unbelievable!");
}
int yearNow = cal.get(Calendar.YEAR);
int monthNow = cal.get(Calendar.MONTH);
int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(birthDate);
int yearBirth = cal.get(Calendar.YEAR);
int monthBirth = cal.get(Calendar.MONTH);
int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
int age = yearNow - yearBirth;
if (monthNow <= monthBirth) {
if (monthNow == monthBirth) {
if (dayOfMonthNow < dayOfMonthBirth) {
age--;
} else {
}
} else {
age--;
}
} else {
}
return age + "";
}
@SuppressWarnings("deprecation")
public static int getIntAge(Date brithday) {
if (brithday != null) {
int dateMiss = Calendar.getInstance().getTime().getDate() - brithday.getDate();// 日差距
int monthMiss = Calendar.getInstance().getTime().getMonth() - brithday.getMonth();// 月份差距
int yearMiss = Calendar.getInstance().getTime().getYear() - brithday.getYear();// 年份差距
if (monthMiss > 0 || (monthMiss == 0 && dateMiss >= 0)) {
return yearMiss;
} else {
return yearMiss - 1;// 周歲少兩歲,SO在去掉一年
}
}
return 0;
}
/**
* 根據(jù)周幾的數(shù)字標(biāo)記獲得周幾的漢字描述
*/
public static String getCnWeekDesc(int weekNum) {
String strWeek = "";
switch (weekNum) {
case 1:
strWeek = "周一";
break;
case 2:
strWeek = "周二";
break;
case 3:
strWeek = "周三";
break;
case 4:
strWeek = "周四";
break;
case 5:
strWeek = "周五";
break;
case 6:
strWeek = "周六";
break;
case 7:
strWeek = "周日";
break;
}
return strWeek;
}
/**
* 獲得"上下午"標(biāo)識(shí)
*
* @param date
* @return
*/
public static String getCnAMPM(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
if (Calendar.AM == cal.get(Calendar.AM_PM))
return "上午";
else
return "下午";
}
/**
* 判斷兩個(gè)日期是否相等
*
* @param d1 日期1
* @param d2 日期2
* @return
*/
public static boolean isTimeEquals(Date d1, Date d2) {
if (d1 == null || d2 == null)
return false;
return Math.abs(d1.getTime() - d2.getTime()) < 50;
}
/**
* 獲取一個(gè)日期的年份
*
* @param date 日期
* @return
*/
public static int getYear(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal.get(Calendar.YEAR);
}
/**
* 獲取一個(gè)日期的月份
*
* @param date 日期
* @return
*/
public static int getMonthOfYear(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal.get(Calendar.MONTH);
}
/**
* 獲取一個(gè)日期的天數(shù)
*
* @param date
* @return
*/
public static int getDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_MONTH);
}
/**
* 獲取一個(gè)日期的小時(shí)數(shù)
*
* @param date
* @return
*/
public static int getHour(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.HOUR_OF_DAY);
}
/**
* 獲取一個(gè)日期的分鐘
*
* @param date 日期
* @return
*/
public static int getMinute(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.MINUTE);
}
/**
* 獲取一個(gè)日期的秒數(shù)
*
* @param date 日期
* @return
*/
public static int getSecond(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.SECOND);
}
/**
* 獲取一個(gè)月的最大天數(shù)
*
* @param year 年份
* @param month 月份
* @return
*/
public static int getMaxDayOfMonth(int year, int month) {
if (month == 1 && isLeapYear(year)) {
return 29;
}
return DAY_OF_MONTH[month];
}
/**
* 判斷是否是潤(rùn)年
*
* @param year 年份
* @return
*/
public static boolean isLeapYear(int year) {
Calendar calendar = Calendar.getInstance();
return ((GregorianCalendar) calendar).isLeapYear(year);
}
/**
* 得到本周的起始時(shí)間
*
* @param currentDate
* @return
*/
public static Date getBeginDateofThisWeek(Date currentDate) {
Calendar current = Calendar.getInstance();
current.setTime(currentDate);
int dayOfWeek = current.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == 1) { // 如果是星期天,星期一則往前退6天
current.add(Calendar.DAY_OF_MONTH, -6);
} else {
current.add(Calendar.DAY_OF_MONTH, 2 - dayOfWeek);
}
current.set(Calendar.HOUR_OF_DAY, 0);
current.set(Calendar.MINUTE, 0);
current.set(Calendar.SECOND, 0);
current.set(Calendar.MILLISECOND, 0);
return current.getTime();
}
@SuppressWarnings("deprecation")
public static void main(String[] args) {
Date addYearDate = getAddYearDate(new Date(), 2);
System.out.println(formatDateYMDHMS(addYearDate));
}
/**
* 轉(zhuǎn)化時(shí)間從指定格式日期為長(zhǎng)整形
*
* @param format
* @param time
* @return
*/
public static Long convertDateStringToDateLong(String format, String time) throws ParseException {
if (time == null || time.trim().equals("")) {
return null;
}
SimpleDateFormat fmt = new SimpleDateFormat(format);
Date d = fmt.parse(time);
return d.getTime();
}
/**
* 獲得指定格式日期
*
* @param date 日期
* @param format 指定格式
* @return
*/
public static Date getFormatDate(Date date, String format) {
if (null == date) {
return null;
}
if (null == format) {
return parseDate(formatDate("yyyy-MM-dd", date), "yyyy-MM-dd");
}
return parseDate(formatDate(format, date), format);
}
public static int getMinuteBetween(Date d1, Date d2) {
if (d1 == null || d2 == null)
return 0;
long m = d1.getTime();
long n = d2.getTime();
return (int) ((m - n) / 60000);
}
/**
* 計(jì)算創(chuàng)建時(shí)間到現(xiàn)在過(guò)去多久了
*
* @param createTime
* @return
*/
public static String getPastTime(Date createTime) {
String pastTime;
Date current = new Date();
int days = getDayBetween(current, createTime);
int hours = 0;
int mins = 0;
if (days > 0) {
pastTime = "1天前";
} else if ((hours = getHourBetween(current, createTime)) > 0) {
pastTime = hours + "小時(shí)前";
} else if ((mins = getMinuteBetween(current, createTime)) > 0) {
pastTime = mins + "分鐘前";
} else {
long seconds = getSecondBetweem(current, createTime);
if (seconds > 5) {
pastTime = seconds + "秒前";
} else {
pastTime = "剛剛";
}
}
return pastTime;
}
/**
* 獲取從今天開(kāi)始未來(lái)一周的星期和日期的映射表 1-星期一:2014-05-12,2-星期二:2014-05-13.....
*
* @return
*/
public static Map<String, Date> getDateForWeekDay() {
Map<String, Date> weekDayDateMap = new HashMap<String, Date>();
Calendar calendar = Calendar.getInstance();
for (int i = 1; i <= 7; i++) {
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
if (dayOfWeek == 0) {
dayOfWeek = 7;
}
weekDayDateMap.put(dayOfWeek + "", calendar.getTime());
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
return weekDayDateMap;
}
/**
* 獲得本日星期數(shù),星期一:1,星期日:7 如果傳入null則默認(rèn)為本日
*
* @return
*/
public static int getDayOfWeek(Calendar calendar) {
int today;
if (calendar != null) {
today = calendar.get(Calendar.DAY_OF_WEEK);
} else {
today = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
}
if (today == 1)
return 7;
else
return today - 1;
}
/**
* 獲取日期的中國(guó)式星期幾(1-7分別代表周一至周日)
*
* @param date
* @return
*/
public static int getDayOfWeek(Date date) {
if (date == null) {
date = new Date();
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return getDayOfWeek(cal);
}
/**
* 判斷兩個(gè)日期是否為同一天
*
* @param date1
* @param date2
* @return
*/
public static boolean isSameDate(Date date1, Date date2) {
if (date1 == null || date2 == null) {
return false;
}
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
calendar1.setTime(date1);
calendar2.setTime(date2);
if (calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR)
&& calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH)
&& calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH)) {
return true;
}
return false;
}
public static String formatDuration(long duration) {
float secondUnit = 1000;
String formatDuration = "";
DecimalFormat decimalFormat = new DecimalFormat(".00");
if (duration < secondUnit) {
formatDuration = duration + "(毫秒)";
} else if (duration < secondUnit * 60) {
formatDuration = decimalFormat.format(duration / secondUnit) + "(秒)";
} else if (duration < secondUnit * 3600) {
formatDuration = decimalFormat.format(duration / (secondUnit * 60)) + "(分鐘)";
} else if (duration < secondUnit * 3600 * 60) {
formatDuration = decimalFormat.format(duration / (secondUnit * 3600)) + "(小時(shí))";
} else {
formatDuration = decimalFormat.format(duration / (secondUnit * 3600 * 24)) + "(天)";
}
return formatDuration;
}
public static long getTodayBeginTime() {
return getDayBegin(new Date()).getTime();
}
public static long getTodayEndTime() {
return getDayEnd(new Date()).getTime();
}
/**
* 比較兩個(gè)時(shí)間大小
*
* @param startTime
* @param endTime
* @return int
* @method compareDate()
*/
public static int compareDate(String startTime, String endTime) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d1 = sdf.parse(startTime);
Date d2 = sdf.parse(endTime);
return d1.compareTo(d2);
}
/**
* 是否是一個(gè)日期格式
* @param time
* @param pattern
* @return
*/
public static boolean isTime(String time,String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
try {
sdf.setLenient(false);
sdf.parse(time);
} catch (ParseException e) {
return false;
}
return true;
}
/**
* 轉(zhuǎn)換時(shí)間標(biāo)準(zhǔn)格式 yyyy-MM-dd HH:mm:ss
*/
public static final ThreadLocal<DateFormat> yMdHms = new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
};
/**
* 轉(zhuǎn)換時(shí)間標(biāo)準(zhǔn)格式 yyyy-MM-dd
*/
public static final ThreadLocal<DateFormat> yMd = new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}
};
/**
* 轉(zhuǎn)換時(shí)間標(biāo)準(zhǔn)格式 yyyy-MM-dd HH:mm
*/
public static final ThreadLocal<DateFormat> yMdHm = new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm");
}
};
/**
* 校驗(yàn)時(shí)間沖突
* @param dateA 2021-02-08 13:00~2021-02-08 13:00
* @param dateB 2021-02-08 13:00~2021-02-08 13:00
* @return 沖突返回true,不沖突返回false
*/
public static Boolean checkDateConflict(String dateA, String dateB) {
List<String> dateAList = new ArrayList<>(Arrays.asList(dateA.split("~")));
List<String> dateBList = new ArrayList<>(Arrays.asList(dateB.split("~")));
try {
Date dateA1 = DateUtil.yMdHm.get().parse(dateAList.get(0));
Date dateA2 = DateUtil.yMdHm.get().parse(dateAList.get(1));
Date dateB1 = DateUtil.yMdHm.get().parse(dateBList.get(0));
Date dateB2 = DateUtil.yMdHm.get().parse(dateBList.get(1));
//dateA開(kāi)始時(shí)間大于dateB結(jié)束時(shí)間,不沖突
if (dateA1.compareTo(dateB2) >= 0) {
return false;
}
//dateA結(jié)束時(shí)間小于dateB開(kāi)始時(shí)間,不沖突
if (dateA2.compareTo(dateB1) <= 0) {
return false;
}
} catch (ParseException e) {
throw new MessageException("時(shí)間格式異常");
}
return true;
}
/**
* 計(jì)算一個(gè)日期N天后的時(shí)間
* @param date
* @param n
* @return
* @throws ParseException
*/
public static String afterNDay(Date date,int n){
Calendar c=Calendar.getInstance();
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
c.setTime(date);
c.add(Calendar.DATE,n);
Date d2=c.getTime();
String s=df.format(d2);
return s;
}
/**
* 計(jì)算兩個(gè)日期相差了多少天
* @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;
}
/**
* 計(jì)算兩個(gè)字符串日期(格式“yyyy-MM-dd”)相差了多少天
* @param date1
* @param date2
* @return
*/
public static int differentStrDaysByMillisecond(String date1,String date2) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date parse1 = null;
Date parse2 = null;
try {
parse1 = sdf.parse(date1);
parse2 = sdf.parse(date2);
} catch (ParseException e) {
e.printStackTrace();
}
int days = (int) ((parse1.getTime() - parse2.getTime()) / (1000*3600*24));
return days;
}
/**
* 獲取本周周一 yyyy-MM-dd
* @return
*/
public static String getWeekBegin(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
//設(shè)置一個(gè)星期的第一天,按中國(guó)的習(xí)慣一個(gè)星期的第一天是星期一
cal.setFirstDayOfWeek(Calendar.MONDAY);
//獲得當(dāng)前日期是一個(gè)星期的第幾天
int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
if(dayWeek==1){
dayWeek = 8;
}
// 根據(jù)日歷的規(guī)則,給當(dāng)前日期減去星期幾與一個(gè)星期第一天的差值
cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - dayWeek);
Date mondayDate = cal.getTime();
String weekBegin = sdf.format(mondayDate);
return weekBegin;
}
/**
* 獲取本周周一 yyyy-MM-dd
* @return
*/
public static String getWeekEnd(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
//設(shè)置一個(gè)星期的第一天,按中國(guó)的習(xí)慣一個(gè)星期的第一天是星期一
cal.setFirstDayOfWeek(Calendar.MONDAY);
//獲得當(dāng)前日期是一個(gè)星期的第幾天
int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
if(dayWeek==1){
dayWeek = 8;
}
cal.add(Calendar.DATE, 4 +cal.getFirstDayOfWeek());
Date sundayDate = cal.getTime();
String weekEnd = sdf.format(sundayDate);
return weekEnd;
}
}4.調(diào)用工具類方法
public static void main(String[] args) {
String date = "2023-07-12";
String yearHoliday = HolidayUtil.isWorkingDay(date);
System.out.println(yearHoliday);
}
打印結(jié)果:0
搞定收工
總結(jié)
到此這篇關(guān)于如何用JAVA判斷當(dāng)前時(shí)間是否為節(jié)假日、周末、工作日及調(diào)休日的文章就介紹到這了,更多相關(guān)JAVA判斷當(dāng)前時(shí)間為節(jié)假日內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java Swing JPasswordField密碼框的實(shí)現(xiàn)示例
這篇文章主要介紹了Java Swing JPasswordField密碼框的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12
selenium-java實(shí)現(xiàn)自動(dòng)登錄跳轉(zhuǎn)頁(yè)面方式
利用Selenium和Java語(yǔ)言可以編寫(xiě)一個(gè)腳本自動(dòng)刷新網(wǎng)頁(yè),首先,需要確保Google瀏覽器和Chrome-Driver驅(qū)動(dòng)的版本一致,通過(guò)指定網(wǎng)站下載對(duì)應(yīng)版本的瀏覽器和驅(qū)動(dòng),在Maven項(xiàng)目中添加依賴,編寫(xiě)腳本實(shí)現(xiàn)網(wǎng)頁(yè)的自動(dòng)刷新,此方法適用于需要頻繁刷新網(wǎng)頁(yè)的場(chǎng)景,簡(jiǎn)化了操作,提高了效率2024-11-11
Java實(shí)現(xiàn)自定義中文排序的方法機(jī)注意事項(xiàng)
在Java中,中文排序通常涉及到使用Collator類來(lái)處理字符串的比較,確保根據(jù)漢字的拼音順序進(jìn)行排序,本文給大家介紹了Java實(shí)現(xiàn)自定義中文排序的方法機(jī)注意事項(xiàng),并有相關(guān)的代碼示例供大家參考,需要的朋友可以參考下2024-10-10
Java中SimpleDateFormat方法超詳細(xì)分析
這篇文章主要給大家介紹了關(guān)于Java中SimpleDateFormat方法超詳細(xì)分析的相關(guān)資料,SimpleDateFormat 是一個(gè)以國(guó)別敏感的方式格式化和分析數(shù)據(jù)的具體類,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-08-08
springboot整合RabbitMQ發(fā)送短信的實(shí)現(xiàn)
本文會(huì)和SpringBoot做整合,實(shí)現(xiàn)RabbitMQ發(fā)送短信,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05
Mybatis通過(guò)Mapper代理連接數(shù)據(jù)庫(kù)的方法
這篇文章主要介紹了Mybatis通過(guò)Mapper代理連接數(shù)據(jù)庫(kù)的方法,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-11-11

