java 获取上周二到下周一的日期
时间: 2024-01-26 14:05:23 浏览: 131
好的,以下是 Java 代码获取上周二到下周一的日期:
```
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
LocalDate today = LocalDate.now();
LocalDate lastTuesday = today.with(TemporalAdjusters.previous(DayOfWeek.TUESDAY));
LocalDate nextMonday = today.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
```
以上代码中,我使用了 `TemporalAdjusters` 类的 `previous()` 方法和 `next()` 方法来获取上周二和下周一的日期。`DayOfWeek` 枚举类表示星期几,这里我使用了 `DayOfWeek.TUESDAY` 和 `DayOfWeek.MONDAY` 来分别表示周二和周一。注意,这里的日期都是本地日期。
相关问题
java 获取本周二到下周一日期 与获取明天日期与获取上周二到本周一日期
获取本周二到下周一日期的Java代码:
```java
import java.time.DayOfWeek;
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate date = LocalDate.now();
LocalDate nextTuesday = date.with(DayOfWeek.TUESDAY);
LocalDate nextMonday = date.with(DayOfWeek.MONDAY).plusWeeks(1);
System.out.println("本周二到下周一日期:");
System.out.println("周二:" + nextTuesday);
System.out.println("周三:" + nextTuesday.plusDays(1));
System.out.println("周四:" + nextTuesday.plusDays(2));
System.out.println("周五:" + nextTuesday.plusDays(3));
System.out.println("周六:" + nextTuesday.plusDays(4));
System.out.println("周日:" + nextTuesday.plusDays(5));
System.out.println("周一:" + nextMonday);
}
}
```
获取明天日期的Java代码:
```java
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate tomorrow = LocalDate.now().plusDays(1);
System.out.println("明天日期:" + tomorrow);
}
}
```
获取上周二到本周一日期的Java代码:
```java
import java.time.DayOfWeek;
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate date = LocalDate.now();
LocalDate lastTuesday = date.with(DayOfWeek.TUESDAY).minusWeeks(1);
LocalDate lastMonday = date.with(DayOfWeek.MONDAY).minusWeeks(1);
System.out.println("上周二到本周一日期:");
System.out.println("上周二:" + lastTuesday);
System.out.println("上周三:" + lastTuesday.plusDays(1));
System.out.println("上周四:" + lastTuesday.plusDays(2));
System.out.println("上周五:" + lastTuesday.plusDays(3));
System.out.println("上周六:" + lastTuesday.plusDays(4));
System.out.println("上周日:" + lastTuesday.plusDays(5));
System.out.println("本周一:" + lastMonday);
}
}
```
java获取本周一、上周一、下周一时间
获取本周一的时间可以使用Java中的Calendar类来处理。下面是一个示例代码:
```java
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
// 获取当前时间的Calendar对象
Calendar calendar = Calendar.getInstance();
// 调整为本周一
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
// 输出本周一的日期
System.out.println("本周一的日期是:" + calendar.getTime());
// 调整为上周一
calendar.add(Calendar.DATE, -7);
// 输出上周一的日期
System.out.println("上周一的日期是:" + calendar.getTime());
// 调整为下周一
calendar.add(Calendar.DATE, 14);
// 输出下周一的日期
System.out.println("下周一的日期是:" + calendar.getTime());
}
}
```
代码中首先获取当前时间的Calendar对象,然后设置其为本周一(通过调整`Calendar.DAY_OF_WEEK`属性为`Calendar.MONDAY`),再输出本周一的日期。然后通过调用`add`方法将日期往前调整7天,得到上周一的日期。最后再将日期往后调整14天(7天加上7天),得到下周一的日期。运行上述代码,即可在控制台输出本周一、上周一和下周一的日期信息。
阅读全文