/**
* 根据年周,获取指定周最早的时间点
*/
public static Date getEarliestDateByYearWeek(Integer yearWeek) {
if (yearWeek == null) {
return null;
}
String yearWeekStr = String.valueOf(yearWeek);
if (yearWeekStr.length() != YEAR_WEEK_LENGTH) {
return null;
}
String year = yearWeekStr.substring(0, 4);
String week = yearWeekStr.substring(4);
// 获取指定年的第一天
Calendar calendar = Calendar.getInstance();
calendar.setMinimalDaysInFirstWeek(7);
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.set(Calendar.YEAR, Integer.parseInt(year));
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.WEEK_OF_YEAR, Integer.parseInt(week));
LocalDate localDate = calendar.getTime().toInstant()
.atZone(ZoneId.systemDefault()).toLocalDate().with(DayOfWeek.MONDAY);
return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
}
/**
* 根据年周,获取指定周最晚的时间点
*/
public static Date getLatestDateByYearWeek(Integer yearWeek) {
if (yearWeek == null) {
return null;
}
String yearWeekStr = String.valueOf(yearWeek);
if (yearWeekStr.length() != YEAR_WEEK_LENGTH) {
return null;
}
String year = yearWeekStr.substring(0, 4);
String week = yearWeekStr.substring(4);
// 获取指定年的第一天
Calendar calendar = Calendar.getInstance();
calendar.setMinimalDaysInFirstWeek(7);
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.set(Calendar.YEAR, Integer.parseInt(year));
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.WEEK_OF_YEAR, Integer.parseInt(week));
LocalDate localDate = calendar.getTime().toInstant()
.atZone(ZoneId.systemDefault()).toLocalDate().with(DayOfWeek.SUNDAY);
return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
}
/**
* 获取指定日期的年周信息
*/
public static int getYearWeek(Date date) {
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate monday = localDate.with(DayOfWeek.MONDAY);
WeekFields weekFields = WeekFields.of(DayOfWeek.MONDAY, 7);
int week = monday.get(weekFields.weekOfYear());
String weekStr = StringUtils.leftPad(String.valueOf(week), 2, "0");
return Integer.parseInt(monday.getYear() + weekStr);
}
Java中年周的相关计算
最新推荐文章于 2023-08-18 10:17:46 发布