编程中经常遇到日期计算,由于项目中使用到按周统计数据,但是mysql中按所在月的周数周统计比较麻烦,于是采用所在年的周数作为分组条件,再通过java计算日期属于年的第一周来进行二次计算,提高性能。
找了下计算指定日期为本年第几周的方法,发现没有现成的api,但网上给出的方法大部分都有个缺陷:
若12月31日是 周最后一天(有的以周一为每周的第一天,有的以周日为周的第一天),则计算正常,否则所在周会被计算为下一年的第一周,于是做此记录。
java8及以上版本可以采用localdate/localdatetime
/** 获取当年的第几周,返回值范围为1-53 */
public static int getweekofyear(localdate date) {
temporalfield field = weekfields.of(locale.getdefault()).weekofweekbasedyear();
int week = date.get(field);
// 12-31会被计算为下一年的第1周,所以需要特殊处理
if (week == 1 && getlocaldate().getmonth() == month.december) {
return localdate.of(date.getyear(), 12,31)// 直接使用指定日期的12月31日作为锚点
.adddays(-7)// 往上推一周,一定是本年倒数第二周
.getlocaldate().get(field) + 1;
}
return week;
}
java8以下版本使用calendar
public static int getweekofyear(date date) {
calendar calendar = calendar.getinstance(locale.getdefault());
calendar.settime(date);
calendar.setfirstdayofweek(calendar.sunday); // 设置每周的第一天为星期日
int week = calendar.get(calendar.week_of_year);
if (week == 1 && calendar.get(calendar.month) == calendar.december) {
calendar.add(calendar.day_of_month, -7);
return calendar.get(calendar.week_of_year) + 1;
}
return week;
}
以周日为每周第一天为例,运行结果如下

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论