java 获取包含当前日期到本年年初的月份string类型数组按日期顺序排列
你可以使用java.time.LocalDate类来获取当前日期和本年年初的日期,然后使用循环来获取每个月份的字符串表示。最后,你可以使用java.util.Arrays.sort()方法对字符串数组进行排序。
下面是一个示例代码:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
LocalDate currentDate = LocalDate.now();
LocalDate yearStart = LocalDate.of(currentDate.getYear(), 1, 1);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
int numMonths = currentDate.getMonthValue() - 1 + 12 - yearStart.getMonthValue() + 1;
String[] months = new String[numMonths];
for (int i = 0; i < numMonths; i++) {
LocalDate month = yearStart.plusMonths(i);
months[i] = month.format(formatter);
}
Arrays.sort(months);
System.out.println(Arrays.toString(months));
}
}
这个代码首先获取当前日期和本年年初的日期。然后,使用DateTimeFormatter将日期格式化为"yyyy-MM"字符串格式。接下来,计算从年初到当前日期的月份数,并创建一个对应大小的字符串数组。使用循环遍历每个月份,并将其格式化为字符串后存储在数组中。最后,使用Arrays.sort()方法对字符串数组进行排序,并将结果打印出来。
注意:在这个示例中,月份的字符串格式为"yyyy-MM",你可以根据需要自行调整
原文地址: https://www.cveoy.top/t/topic/hXBF 著作权归作者所有。请勿转载和采集!