package com.example.demo.Utils;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
/**
* 周工具类
*/
public class WeekUtils {
/**
* 获取指定日期所在周的周数
*
* @param date 日期对象
* @return 周数
*/
public static int getWeekNumber(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.WEEK_OF_YEAR);
}
/**
* 获取当前日期所在周的周数
*
* @return 周数
*/
public static int getCurrentWeekNumber() {
return getWeekNumber(new Date());
}
/**
* 解析日期字符串
*
* @param dateString 日期字符串
* @param format 日期格式
* @return 解析后的日期对象
* @throws ParseException 解析异常
*/
/**
* 获取两个日期之间的周数差
*
* @param startDate 起始日期
* @param endDate 结束日期
* @return 周数差
*/
public static int getWeeksBetween(Date startDate, Date endDate) {
Calendar startCalendar = Calendar.getInstance();
startCalendar.setTime(startDate);
int startWeek = startCalendar.get(Calendar.WEEK_OF_YEAR);
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endDate);
int endWeek = endCalendar.get(Calendar.WEEK_OF_YEAR);
int yearDiff = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
if (yearDiff == 0) {
return endWeek - startWeek;
} else {
int weeksInYear = startCalendar.getActualMaximum(Calendar.WEEK_OF_YEAR);
return (weeksInYear - startWeek + endWeek) + (yearDiff - 1) * weeksInYear;
}
}
/**
* 获取当前日期与指定日期之间的周数差
*
* @param endDate 指定日期
* @return 周数差
*/
public static int getWeeksBetweenCurrentAnd(Date endDate) {
return getWeeksBetween(new Date(), endDate);
}
}