如何获得当前日期之前的最后一个星期天?

我有以下代码来获取当前日期之前的最后一个星期日:

Calendar calendar=Calendar.getInstance(); calendar.set(Calendar.WEEK_OF_YEAR, calendar.get(Calendar.WEEK_OF_YEAR)-1); calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); Log.e("first day", String.valueOf(calendar.get(Calendar.DAY_OF_MONTH))); 

但是这段代码不起作用。 请告诉我,我该如何解决?

这会奏效。 我们首先得到日计数,然后在当天减去它并加1(星期日)

 Calendar cal=Calendar.getInstance(); cal.add( Calendar.DAY_OF_WEEK, -(cal.get(Calendar.DAY_OF_WEEK)-1)); System.out.println(cal.get(Calendar.DATE)); 

这可以通过TemporalAdjusters (仅限Java 8+)轻松实现。

  LocalDate.now().with(TemporalAdjusters.previous(DayOfWeek.SUNDAY)) 

如果今天是星期天,你想获得当天,那么:

  LocalDate.now().with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY)) 

您可以在一天的步骤中重复,直到您在星期天到达:

 Calendar cal = Calendar.getInstance(); while (cal.get( Calendar.DAY_OF_WEEK ) != Calendar.SUNDAY) cal.add( Calendar.DAY_OF_WEEK, -1 ); 

或者,仅在一个步骤中,减去星期日和现在之间的天数差异:

 Calendar cal = Calendar.getInstance(); int dayOfTheWeek = cal.get( Calendar.DAY_OF_WEEK ); cal.add( Calendar.DAY_OF_WEEK, Calendar.SUNDAY - dayOfTheWeek ); 

以下是使用Joda计算任何上周工作日的片段:

 import org.joda.time.DateTime import org.joda.time.DateTimeConstants DateTime now = DateTime(); int offset = ((now.dayOfWeek - DateTimeConstants.THURSDAY) + 7) % 7; DateTime lastThursday = now.minusDays(offset); 

只需将DateTimeConstants.THURSDAY替换为您选择的日期。

 final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(cal.getTimeInMillis() // // Saturday is the 7th day of week, so use modulo to get it : remove day between todoay - (( cal.get(Calendar.DAY_OF_WEEK) % 7) * 86400000)); // 86400000=24*60*60*1000 System.out.println(cal.getTime()); . . . 

无论哪个月份和年份,以下内容均适用于我。

  Calendar cal = Calendar.getInstance(TimeZone.getDefault()); Date date = cal.getTime(); int days = cal.get(Calendar.DAY_OF_WEEK) - Calendar.SUNDAY; date.setTime(date.getTime() - (long) (days*1000*60*60*24)); cal.setTime(date);