java 获取本周起止时间
时间: 2023-07-04 07:30:05 浏览: 57
以下是获取本周起止时间的 Java 代码:
```java
import java.time.DayOfWeek;
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate monday = today;
LocalDate sunday = today;
while (monday.getDayOfWeek() != DayOfWeek.MONDAY) {
monday = monday.minusDays(1);
}
while (sunday.getDayOfWeek() != DayOfWeek.SUNDAY) {
sunday = sunday.plusDays(1);
}
System.out.println("本周起始日期:" + monday);
System.out.println("本周结束日期:" + sunday);
}
}
```
该代码使用 `java.time.LocalDate` 类获取当前日期,并通过循环找到本周的周一和周日。最后输出本周的起始日期和结束日期。
相关问题
java获取本周起止时间
以下是 Java 获取本周起止时间的代码:
```
Calendar calendar = Calendar.getInstance();
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
calendar.add(Calendar.DAY_OF_WEEK, 1 - dayOfWeek);
Date startDate = calendar.getTime();
calendar.add(Calendar.DAY_OF_WEEK, 6);
Date endDate = calendar.getTime();
```
这段代码获取了当前时间所在的周的起始日期和结束日期,其中起始日期为周一,结束日期为周日。
java 获取本周起止时间 返回Date
可以使用以下代码获取本周的起止时间:
```java
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate startOfWeek = today.with(DayOfWeek.MONDAY);
LocalDate endOfWeek = today.with(DayOfWeek.SUNDAY);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String startOfWeekStr = startOfWeek.format(formatter);
String endOfWeekStr = endOfWeek.format(formatter);
System.out.println("本周起始时间:" + startOfWeekStr);
System.out.println("本周结束时间:" + endOfWeekStr);
}
}
```
输出结果如下:
```
本周起始时间:2022-02-28
本周结束时间:2022-03-06
```
阅读全文