我遇到了一个简单的问题,我解决了(我没有放弃)。然而,我认为有一些更简洁和棘手的解决方案。 问题如下:返回今天之前最后 X 天的日期。例如,如果今天是 2013 年 7 月 9 日星期二,而我想要最后一个星期五,则答案将为 2013 年 7 月 5 日星期五。
我的解决方案如下:
public Date dateOfLast(int day) {
int today = calendar.get(Calendar.DAY_OF_WEEK);
int daysDifferences = today - day;
int daysToSubtract;
if (day < today) {
//last day seems to be in current week !
//for example Fr > Tu.
daysToSubtract = -(Math.abs(daysDifferences));
} else {
//7- ( difference between days )!
//last day seems to be in the previous,thus we subtract the the days differences from 7
// and subtract the result from days of month.
daysToSubtract = -(7 - Math.abs(daysDifferences));
}
//subtract from days of month.
calendar.add(Calendar.DAY_OF_MONTH, daysToSubtract);
return calendar.getTime();
}
有人给我一个数学公式或更简单的解决方案(如果有的话)吗?
最佳答案
int daysToSubtract = ((today - day) + 7) % 7;
如果我没记错的话,应该没问题。
例如
today = 4
day = 2
daysToSubtract = ((4 - 2) + 7) % 7 = 2 : correct
today = 2
day = 4
daysToSubtract = ((2 - 4) + 7) % 7 = 5 : correct
关于java - 获取今天起最后 "X"天?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17559364/