package com.alipay.airbops.common.service.integration.util;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class CalenderUtil {
/**
* Description: 判断一个时间是否在一个时间段内 </br>
*
* @param nowTime 当前时间 </br>
*/
public static boolean belongCalendar(Date nowTime) {
Calendar date = Calendar.getInstance();
date.setTime(nowTime);
Calendar begin = Calendar.getInstance();
begin.setTime(lastThursday());
Calendar end = Calendar.getInstance();
end.setTime(thisWednesday());
return date.after(begin) && date.before(end);
}
public static boolean isThisWeek(Long time) {
if (time == null) {
return false;
}
Calendar calendar = Calendar.getInstance();
int currentWeek = calendar.get(Calendar.WEEK_OF_YEAR);
calendar.setTime(new Date(time));
int paramWeek = calendar.get(Calendar.WEEK_OF_YEAR);
if (paramWeek == currentWeek) {
return true;
}
return false;
}
public static boolean isThisYear(Long time) {
if (time == null) {
return false;
}
Calendar calendar = Calendar.getInstance();
int currentYear = calendar.get(Calendar.YEAR);
calendar.setTime(new Date(time));
int paramYear = calendar.get(Calendar.YEAR);
if (paramYear == currentYear) {
return true;
}
return false;
}
/**
* 获取上周四时间
*/
private static Date lastThursday() {
//作用防止周日得到本周日期
Calendar calendar = Calendar.getInstance();
while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
calendar.add(Calendar.DAY_OF_WEEK, -1);
}
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
int offset = 7 - dayOfWeek;
calendar.add(Calendar.DATE, offset - 9);
return getFirstDayOfWeek(calendar.getTime(), 5);//这是从上周日开始数的到上周五为6
}
/**
* 得到本周周三日期
*/
private static Date thisWednesday() {
Calendar cal = new GregorianCalendar();
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek() + 2);
cal.set(Calendar.HOUR_OF_DAY, 23);//指示一天中的小时。HOUR_OF_DAY 用于 24 小时制时钟。例如,在 10:04:15.250 PM 这一时刻,HOUR_OF_DAY 为 22。
cal.set(Calendar.MINUTE, 59);//指示一小时中的分钟。例如,在 10:04:15.250 PM 这一时刻,MINUTE 为 4。
cal.set(Calendar.SECOND, 59);
Date last = cal.getTime();
return last;
}
/**
* 得到某一天的该星期的第一日 00:00:00
*
* @param date
* @param firstDayOfWeek 一个星期的第一天为星期几
* @return
*/
private static Date getFirstDayOfWeek(Date date, int firstDayOfWeek) {
Calendar cal = Calendar.getInstance();
if (date != null) {
cal.setTime(date);
}
cal.setFirstDayOfWeek(firstDayOfWeek);//设置一星期的第一天是哪一天
cal.set(Calendar.DAY_OF_WEEK, firstDayOfWeek);//指示一个星期中的某天
cal.set(Calendar.HOUR_OF_DAY, 0);//指示一天中的小时。HOUR_OF_DAY 用于 24 小时制时钟。例如,在 10:04:15.250 PM 这一时刻,HOUR_OF_DAY 为 22。
cal.set(Calendar.MINUTE, 0);//指示一小时中的分钟。例如,在 10:04:15.250 PM 这一时刻,MINUTE 为 4。
cal.set(Calendar.SECOND, 0);
return cal.getTime();
}
}
Calendar工具类的日常使用--保持持续更新中
最新推荐文章于 2023-03-01 10:52:28 发布