package com.alpari.wang.utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Calendar;
import java.util.Date;
@Slf4j
@Component
public class DateUtils {
private DateUtils() {
}
/**
* 根据year年所在第week周,获取周一的时间,以及所在月份 获取Calendar
* @param year 年份
* @param week 当前年所在的第几周,以每年的第一个周一为第一周
* @return 获取Calendar 可获取周一的时间,以及所在月份
*/
public static Calendar weekToDayFormate(Integer year, Integer week){
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.WEEK_OF_YEAR, week);
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
//一年第一周最小天数为4天,按照iso标准计算
cal.setMinimalDaysInFirstWeek(4);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal;
}
/**
* 根据任意日期获取当前周周一时间
* @param date
* @return
*/
public static Date getMonday(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.setFirstDayOfWeek(Calendar.MONDAY);
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
return org.apache.commons.lang3.time.DateUtils.truncate(c.getTime(), Calendar.DATE);
}
/**
* 获取入参时间所在年周xxxx年xx周6位
* @param date
* @return
*/
public static String getYearWeek(Date date) {
Calendar cal = Calendar.getInstance();
//设置一周起始时间为周一
cal.setFirstDayOfWeek(Calendar.MONDAY);
//一年第一周最小天数为4天,按照iso标准计算
cal.setMinimalDaysInFirstWeek(4);
cal.setTime(date);
//设置装运日期所在的年周
String yearWeek;
//跨年,当前时间为一月初,按照iso算法为去年的第52或者53周,故年分减一
if(cal.get(Calendar.MONTH) + 1 == 1 && 52 <= cal.get(Calendar.WEEK_OF_YEAR)) {
yearWeek = cal.get(Calendar.YEAR) - 1 + String.format("%02d", cal.get(Calendar.WEEK_OF_YEAR));
}
//当前时间为12月,按照iso算法周数为下一年第一周,故年份加一
else if(cal.get(Calendar.MONTH) + 1 == 12 && 1 == cal.get(Calendar.WEEK_OF_YEAR)) {
yearWeek = cal.get(Calendar.YEAR) + 1 + String.format("%02d", cal.get(Calendar.WEEK_OF_YEAR));
}
else {
yearWeek = cal.get(Calendar.YEAR) + String.format("%02d", cal.get(Calendar.WEEK_OF_YEAR));
}
return yearWeek;
}
}
标签:set,return,MONDAY,获取,当前,cal,date,周一,Calendar
From: https://www.cnblogs.com/alpari-wang/p/17446037.html