gpt4 book ai didi

java - 使用java获取当前周的剩余日期

转载 作者:行者123 更新时间:2023-12-01 12:31:04 26 4
gpt4 key购买 nike

我正在使用以下代码来获取当前日期和下一个日期。

List<String> list=new ArrayList();
int nextWeekId=2;
int currentWeekId=1;

LocalDate localDate = LocalDate.now();
for (int i = 0; i < list.size(); i++) {
if (i >= 7) {
saveDetails(nextWeekId,list.get(i), java.sql.Date.valueOf(localDate.plusDays(i)));
} else {
saveDetails(currentWeekId, list.get(i), java.sql.Date.valueOf(localDate.plusDays(i)));
}
}
我的 list大小总是 size = 14 .一周应该总是从 Monday 开始.我想要,如果例如今天是 Friday日期是 2020-07-10 .然后我的系统将存储日期 2020-07-10 , 2020-07-11 , 2020-07-12反对 currentWeekId以及接下来的 7 天对 nextWeekId .
访问值的顺序无关紧要。

最佳答案

为了获得本周的剩余天数,您需要从当前日期迭代到下一个星期一,如下所示:

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;

public class Main {
public static void main(String[] args) {
LocalDate localDate = LocalDate.now();
LocalDate firstDayOfNextWeek = localDate.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
while (localDate.isBefore(firstDayOfNextWeek)) {
System.out.println(localDate);
localDate = localDate.plusDays(1);
}
}
}
输出:
2020-07-11
2020-07-12
请注意 LocalDate#with 返回目标对象的副本,其中一个元素发生了变化;这是不可变的等价于 set JavaBean 上的方法。
[更新]:下面给出的是另一种方法(Cortesy: Basil Bourque):
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
LocalDate localDate = LocalDate.now();
LocalDate firstDayOfNextWeek = localDate.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
List<LocalDate> remainingDays = localDate.datesUntil(firstDayOfNextWeek)
.collect(Collectors.toList());
System.out.println(remainingDays);
}
}
输出:
[2020-07-11, 2020-07-12]
查询 LocalDate#datesUntil 了解更多信息。
【又一更新】
发布此更新以帮助 OP 列出下一周的所有日子:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
LocalDate localDate = LocalDate.now();

// Remaining days of the current week
LocalDate firstDayOfNextWeek = localDate.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
List<LocalDate> remainingDays = localDate.datesUntil(firstDayOfNextWeek).collect(Collectors.toList());
System.out.println(remainingDays);

// Days of next week
LocalDate firstDayOfNextToNextWeek = firstDayOfNextWeek.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
List<LocalDate> daysOfNextWeek = firstDayOfNextWeek.datesUntil(firstDayOfNextToNextWeek)
.collect(Collectors.toList());
System.out.println(daysOfNextWeek);
}
}
输出:
[2020-07-11, 2020-07-12]
[2020-07-13, 2020-07-14, 2020-07-15, 2020-07-16, 2020-07-17, 2020-07-18, 2020-07-19]

关于java - 使用java获取当前周的剩余日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62852288/

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