我对当前日期之前获得的最后一个星期日下面的代码:
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 );
这里是一个片段计算与乔达一周的任何最后一天:
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);