Java当前时间为周日时,获取上周一和上周日时间
时间: 2024-05-02 21:19:05 浏览: 60
您可以使用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);
}
}
```
java获取上周的周五
要获取上周的周五,可以使用Java的Calendar类来实现。以下是一个示例代码:
```java
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.WEEK_OF_YEAR, -1); // 将日期设置为上周
calendar.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY); // 将日期设置为周五
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1; // 月份从0开始,需要加1
int day = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println("上周的周五日期为:" + year + "-" + month + "-" + day);
}
}
```
这段代码首先获取当前日期的Calendar实例,然后将日期设置为上周,最后将日期设置为周五。最后通过get方法获取年、月、日,并输出结果。
请注意,此代码假设一周的第一天为周日。如果你的周的第一天是不同的,需要使用`setFirstDayOfWeek()`方法来设置。
阅读全文