我遇到了一個簡單的問題,我解決了(我沒有放棄)。不過,我認爲還有一些更爲巧妙和棘手的解決方案。 問題如下:返回今天之前最後X天的日期。例如,如果今天是星期二,2013年7月,我想最後一個星期五的答案將是週五,7月05日,2013年從今天開始獲取最後的「X」天嗎?
我的解決方案如下:
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();
}
誰能給我一個數學公式還是更簡單的解決方案?
您的解決方案對我來說很好。 – arshajii
謝謝,但我認爲有更好的一個 – Adelin