Java当前时间为周日时,获取上周一和上周日时间
时间: 2024-05-02 08:19:05 浏览: 64
您可以使用Java中的Calendar类来获取上周一和上周日的时间。以下是示例代码:
```
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
// 获取当前时间
Calendar now = Calendar.getInstance();
now.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); // 设置为周一
now.add(Calendar.DATE, -7); // 减去7天,即为上周一
System.out.println("上周一的时间是:" + now.getTime());
now.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); // 设置为周日
now.add(Calendar.DATE, -7); // 减去7天,即为上周日
System.out.println("上周日的时间是:" + now.getTime());
}
}
```
该程序会输出上周一和上周日的时间。请注意,在Java中,一周的第一天是周日,它对应的常量值为1,因此我们需要先将当前时间设置为周一,然后再减去7天,即可得到上周一的时间。同理,我们可以将当前时间设置为周日,再减去7天,即可得到上周日的时间。
相关问题
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);
}
}
```
LocalDate 获取上周一日期
在Java中,如果你想要获取当前日期之前的上周一,可以使用`LocalDate`类以及一些时间间隔操作。首先,你需要获取当前日期`LocalDate now = LocalDate.now()`;然后从当前日期减去7天(因为一周有七天),再减去两天(因为我们通常所说的“上周一”是指周日之后的第一个工作日)。这里假设默认工作日是从周一到周五。以下是代码示例:
```java
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public LocalDate getLastMonday() {
LocalDate now = LocalDate.now();
int daysToSubtract = (now.getDayOfWeek() == DayOfWeek.MONDAY) ? 0 : 7 - (now.getDayOfWeek().getValue() - DayOfWeek.MONDAY.getValue());
return now.minusDays(daysToSubtract).minusWeeks(1);
}
```
阅读全文