我有以下代码来获取当前日期之前的最后一个星期日:
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)));
但是这段代码不起作用。请告诉我,我该如何解决?
答案 0 :(得分:20)
这会奏效。我们首先获得日期计数,然后在当天减去该数量并添加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));
答案 1 :(得分:13)
这可以通过TemporalAdjusters(仅限Java 8+)轻松实现。
LocalDate.now().with(TemporalAdjusters.previous(DayOfWeek.SUNDAY))
如果今天是星期天,你想得到当天,那么:
LocalDate.now().with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY))
答案 2 :(得分:5)
你可以在一天的步骤中迭代,直到你到达星期天:
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 );
答案 3 :(得分:1)
以下是使用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
替换为您选择的日期。
答案 4 :(得分:0)
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());
. . .
答案 5 :(得分:0)
以下适用于我,无论是哪个月份。
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);
答案 6 :(得分:0)
以下是使用Kotlin扩展名和Joda Time library的方法。
答案基于linqu的答案,但这也修复了该答案中的错误。
该错误是,如果当前日期与您尝试获取的日期相同,则该日期不起作用。
/**
* E.g., DateTimeConstants.SUNDAY
*/
fun DateTime.previousDayOfWeek(day: Int): DateTime {
var date = this
if(date.dayOfWeek == day) date = date.minusDays(1)
val offset = (date.dayOfWeek - day + 7) % 7
return date.minusDays(offset)
}
fun DateTime.previousSunday(): DateTime {
return previousDayOfWeek(DateTimeConstants.SUNDAY)
}