获取给定日期范围内的字符串日期列表-Scala [英] Get list of string dates between a given date range - Scala
本文介绍了获取给定日期范围内的字符串日期列表-Scala的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试获取Scala中给定范围的字符串日期列表.是否有直接/简短的方法来实现这一目标?
I am trying to get a list of string dates in Scala for a given range. Is there a direct/shorter way to achieve this?
val format = "yyyMMdd"
val startDate = "20200101"
val endDate = "20200131"
预期产量=列表(2020101,20200102,.....,20200131)
Expected Output = List(2020101,20200102, ....., 20200131)
推荐答案
您可以执行以下操作:
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) {
// Tests
System.out.println(getDateList("20200101", "20200110"));
System.out.println(getDateList("20200101", "20200131"));
}
static List<String> getDateList(String strStartDate, String strEndDate) {
// List to be populated with the desired strings
List<String> result = new ArrayList<>();
// Formatter for the desired pattern
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
// Parse strings to LocalDate instances
LocalDate startDate = LocalDate.parse(strStartDate, formatter);
LocalDate endDate = LocalDate.parse(strEndDate, formatter);
// Loop starting with start date until end date with a step of one day
for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
result.add(date.format(formatter));
}
// Return the populated list
return result;
}
}
输出:
[20200101, 20200102, 20200103,..., 20200110]
[20200101, 20200102, 20200103,..., 20200131]
使用Java Stream API的解决方案:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
// Tests
System.out.println(getDateList("20200101", "20200110"));
System.out.println(getDateList("20200101", "20200131"));
}
static List<String> getDateList(String strStartDate, String strEndDate) {
// Formatter for the input and desired pattern
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
// Parse strings to LocalDate instances
LocalDate startDate = LocalDate.parse(strStartDate, formatter);
LocalDate endDate = LocalDate.parse(strEndDate, formatter);
return Stream.iterate(startDate, date -> date.plusDays(1))
.limit(ChronoUnit.DAYS.between(startDate, endDate.plusDays(1)))
.map(date -> date.format(formatter))
.collect(Collectors.toList());
}
}
这篇关于获取给定日期范围内的字符串日期列表-Scala的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文