gpt4 book ai didi

java - 获取从今天开始的最后 "X"天?

转载 作者:行者123 更新时间:2023-12-04 04:50:14 24 4
gpt4 key购买 nike

我遇到了一个简单的问题,我解决了(我没有放弃)。但是,我认为有一些更巧妙和棘手的解决方案。
问题如下:返回今天前最后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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com