编程语言
首页 > 编程语言> > 下一周和前一周在java中盯着和结束日期

下一周和前一周在java中盯着和结束日期

作者:互联网

我想得到一周的开始和结束日期
例如

2012-05-06至2012-05-12
2012-05-13至2012-05-19

我写的代码是

currWeekCalender.add(Calendar.WEEK_OF_YEAR, 1);

    String dateStart =  currWeekCalender.get(Calendar.YEAR) + "-" + addZero((currWeekCalender.get(Calendar.MONTH) + 1)) + "-" + addZero(currWeekCalender.getFirstDayOfWeek());
    currWeekCalender.add(Calendar.DAY_OF_MONTH,7);
    String dateEnd =  currWeekCalender.get(Calendar.YEAR) + "-" + addZero((currWeekCalender.get(Calendar.MONTH) + 1)) + "-" + addZero(currWeekCalender.get(Calendar.DAY_OF_MONTH));

但结果不正确,我也想要前几周的约会.

谢谢

解决方法:

你的问题是getFirstDayOfWeek()返回一周的第一天;例如,周日在美国,周一在法国.它不会返回一个月中的某一天.见javadoc.

本周开始的一个月的第一天是(伪代码)

((7 + (firstDayOfWeek - dayOfWeek(firstOfMonth))) % 7) + 1

如果您愿意,可以将其转换为java.util.Calendar代码,但我建议使用Joda时间代替.

also I want previous weeks date.

可以使用add减去七天

currCalendar.add(Calendar.DAY_OF_MONTH, -7)

这可能涉及下溢,但增加了交易.

add(f, delta)

adds delta to field f. This is equivalent to calling set(f, get(f) + delta) with two adjustments:

Add rule 1. The value of field f after the call minus the value of field f before the call is delta, modulo any overflow that has occurred in field f. Overflow occurs when a field value exceeds its range and, as a result, the next larger field is incremented or decremented and the field value is adjusted back into its range.

标签:dayofweek,java,date,calendar
来源: https://codeday.me/bug/20190726/1538994.html