Java 如何list取值近三年的数据时间为字符串
时间: 2023-12-25 09:06:00 浏览: 28
可以使用 Java 8 的日期时间 API,结合 `DateTimeFormatter` 类和 `LocalDate` 类来实现。
假设你的时间字符串格式为 "yyyy-MM-dd",可以按照以下步骤来获取近三年的数据:
1. 获取当前日期:`LocalDate currentDate = LocalDate.now();`
2. 计算三年前的日期:`LocalDate threeYearsAgo = currentDate.minusYears(3);`
3. 将日期转换为字符串:`String dateStr = threeYearsAgo.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));`
4. 将日期字符串存入 List:`List<String> dates = new ArrayList<>();`,然后在循环中添加日期字符串:`dates.add(dateStr);`
完整代码示例:
```java
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
LocalDate currentDate = LocalDate.now();
LocalDate threeYearsAgo = currentDate.minusYears(3);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
List<String> dates = new ArrayList<>();
for (LocalDate date = threeYearsAgo; date.isBefore(currentDate.plusDays(1)); date = date.plusDays(1)) {
dates.add(date.format(formatter));
}
System.out.println(dates);
}
}
```
输出结果为近三年的所有日期字符串,例如:
```
[2019-06-12, 2019-06-13, 2019-06-14, ..., 2022-06-10, 2022-06-11, 2022-06-12]
```