java中写个方法获取当前时间的第一个月和目前所在月份,月份格式为“yyyy-MM”
时间: 2024-05-10 07:21:19 浏览: 12
您可以使用Java 8中的java.time包中的类来获取当前时间的第一个月和目前所在月份。下面是一个示例方法:
```java
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class DateUtils {
public static String[] getFirstAndCurrentMonth() {
String[] months = new String[2];
LocalDate now = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
// 获取当前时间的第一个月
LocalDate firstOfMonth = now.withDayOfMonth(1);
String firstMonth = firstOfMonth.format(formatter);
// 获取当前时间所在的月份
String currentMonth = now.format(formatter);
months[0] = firstMonth;
months[1] = currentMonth;
return months;
}
}
```
在这个示例中,我们使用`LocalDate`类来获取当前时间和第一个月,并使用`DateTimeFormatter`来格式化月份。方法返回一个包含第一个月和当前月份的字符串数组。您可以使用以下代码来调用此方法:
```java
String[] months = DateUtils.getFirstAndCurrentMonth();
System.out.println("第一个月:" + months[0]);
System.out.println("当前月份:" + months[1]);
```
输出应该类似于以下内容:
```
第一个月:2021-07
当前月份:2021-09
```
相关推荐
![.zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)
![](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)