欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java和mysql的week周次对应方法

程序员文章站 2022-07-08 10:25:40
...
MYSQL方法:
select dt,if(month(dt)=1 and weekofyear(dt)>=52,year(dt)-1,year(dt)) as year,lpad(if(weekofyear(dt)<=1 and month(dt) >= 11,weekofyear(dt)+52,weekofyear(dt)),2,'0') as week from n_match;

JAVA方法
public WeekReportPeriod doPeriod(String dt) {
if (StringUtils.isEmpty(dt)) {
return this;
}
dt = dt.substring(0, 10);
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.setMinimalDaysInFirstWeek(4);// 每年第一周需要4天在本年度内
cal.setTime(VOUtil.parse(dt));
int week = cal.get(Calendar.WEEK_OF_YEAR);
if (week <= 1) {
int month = cal.get(Calendar.MONTH);
if (month >= 11) {
week += 52;
}
}
int year = cal.get(Calendar.YEAR);
if (week >= 52) {
int month = cal.get(Calendar.MONTH);
if (month <= 1) {
year = year - 1;
}
}
return this;
}

验证了从2010-01-01到2029-12-16的数据,其年度和周次完全匹配