java获取当月有几周
时间: 2023-10-20 11:27:48 浏览: 73
您好!要获取当前月份有几周,可以使用 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();
// 获取当前月份
int month = calendar.get(Calendar.MONTH) + 1;
// 创建 SimpleDateFormat 对象,用于格式化日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
// 获取当前月份的第一天
calendar.set(Calendar.DAY_OF_MONTH, 1);
String firstDayOfMonth = sdf.format(calendar.getTime());
// 获取当前月份的最后一天
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
String lastDayOfMonth = sdf.format(calendar.getTime());
// 计算当前月份的周数
int weeks = (int) ((calendar.get(Calendar.DAY_OF_MONTH) - 1 + calendar.get(Calendar.DAY_OF_WEEK)) / 7.0);
// 输出结果
System.out.println(firstDayOfMonth + " ~ " + lastDayOfMonth + " 共 " + weeks + " 周");
}
}
```
这个代码会输出当前月份的第一天、最后一天和周数。其中,计算周数的公式为:
周数 = 当月天数 + 当月第一天是星期几 - 1 ÷ 7
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.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)
![](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)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)