java 获取本周起止时间
时间: 2023-07-05 12:27:57 浏览: 32
要获取本周的起止日期,可以使用 Java 中的 Calendar 类和 SimpleDateFormat 类来实现。以下是获取本周起止时间的示例代码:
```java
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
calendar.add(Calendar.DATE, -(dayOfWeek - 2));
String startDate = sdf.format(calendar.getTime());
calendar.add(Calendar.DATE, 6);
String endDate = sdf.format(calendar.getTime());
System.out.println("本周起始日期:" + startDate);
System.out.println("本周结束日期:" + endDate);
}
}
```
在这个示例中,我们首先获取当前的 Calendar 实例,并使用 SimpleDateFormat 类将日期格式化为“yyyy-MM-dd”格式。接下来,我们使用 get(Calendar.DAY_OF_WEEK) 方法获取当前日期是本周的第几天,并使用 add(Calendar.DATE, - (dayOfWeek - 2)) 方法将日期调整到本周的第一天(假设星期一为一周的第一天)。最后,我们使用 add(Calendar.DATE, 6) 将日期调整到本周的最后一天。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)