2

我确实试图寻找答案,但没有找到。

如果网站上看不到日期,我想决定是否切换以及切换多少周。我试了几天

    LocalDate dateToSelect = parseStringDateToLocalDate(datum);
    LocalDate lastVisibleOrderDate = getLastVisibleOrderDate();
    int daysDifference = Period.between(lastVisibleOrderDate,dateToSelect).getDays();]
    int weeksToSwitch = (daysDifference / 7) + 1;

和期间:

    Long weeks = ChronoUnit.WEEKS.between(lastVisibleOrderDate,dateToSelect);

但是,我不知道如何解释 7 天的差异并且仍然在同一周。

场景:最后可见日期 = 2017-03-12(星期日)要选择的日期 = 2017-03-13(星期一)

差=1。除以7=0,加1,所以切换到下周。这太棒了!作品。

但是,如果要选择的日期是 2017-03-19(星期日),则差 = 7。除以 7 和加 1 = 2。它会切换 2 周,但只需要切换 1。

它应该能够来回切换几周,因此在 lastVisibleOrderDate 上加一天或在 dateToSelect 上减 1 天会带来问题。

我可以这样做(用于积极切换),但这不是我希望的最好的选择:

    if (0 < daysDifference && daysDifference <= 7){

    } else if (7 < daysDifference && daysDifference <=14){

    } else if (14 < daysDifference && daysDifference <=21){

    } else if (21 < daysDifference && daysDifference <=28){

    }

有什么建议么?

4

2 回答 2

3

您想使用ChronoUnit来测量时间。

在您的问题中,您所拥有的 if/else 实际上是在衡量一周 8 天。如果减去两天,则答案是 0,最小的数字是 0,而不是 1。因此,在您的示例中,7 天实际上是一周 + 1 天。

我相信这会让你得到你想要的结果。

LocalDate lastVisible = LocalDate.of(2017, 3, 12);
LocalDate dateToSelect = LocalDate.of(2017, 3, 13).minusDays(1);

long weeks = ChronoUnit.WEEKS.between(lastVisible, dateToSelect);
System.out.println("number of weeks "+ weeks);

dateToSelect = LocalDate.of(2017, 3, 19).minusDays(1);
weeks = ChronoUnit.WEEKS.between(lastVisible, dateToSelect);
System.out.println("number of weeks "+ weeks);

dateToSelect = LocalDate.of(2017, 3, 20).minusDays(1);
weeks = ChronoUnit.WEEKS.between(lastVisible, dateToSelect);
System.out.println("number of weeks "+ weeks);

- 输出 :

number of weeks 0
number of weeks 0
number of weeks 1

但这是为了获得实际的周数。

LocalDate lastVisible = LocalDate.of(2017, 3, 12);
LocalDate dateToSelect = LocalDate.of(2017, 3, 13);

long weeks = ChronoUnit.WEEKS.between(lastVisible, dateToSelect);
System.out.println("number of weeks "+ weeks);

dateToSelect = LocalDate.of(2017, 3, 19);
weeks = ChronoUnit.WEEKS.between(lastVisible, dateToSelect);
System.out.println("number of weeks "+ weeks);

// to get number of weeks regardless of going forward or backwards in time
dateToSelect = LocalDate.of(2017, 3, 20);
weeks = Math.abs(ChronoUnit.WEEKS.between(dateToSelect, lastVisible));
System.out.println("number of weeks "+ weeks);

- 输出:

number of weeks 0
number of weeks 1
number of weeks 1
于 2017-03-10T07:02:37.670 回答
0

您可以使用 double 来避免这种情况:

double daysDifferenceDbl = daysDifference;
double weeksToSwitchDbl = (daysDifferenceDbl / 7) + 1;        
int weeksToSwitch = (int) weeksToSwitchDbl;
于 2017-03-09T16:26:16.930 回答