微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

获取给定日期范围内的字符串日期列表-Scala

如何解决获取给定日期范围内的字符串日期列表-Scala

我正在尝试获取给定范围内Scala中字符串日期的列表。有直接/简短的方法可以实现这一目标吗?

val format = "yyyMMdd"
val startDate = "20200101"
val endDate = "20200131"

预期产量=列表(2020101,20200102,.....,20200131)

解决方法

是的...如果您以给定的格式添加破折号,则可以使用LocalData来解析日期,而无需使用日期格式化程序来使其复杂化。例如yyyy-MM-dd

val startDate = LocalDate.parse("2020-01-01")

val endDate = LocalDate.parse("2020-01-31") 

然后,您可以使用java.time.LocalDate.datesUntil为您生成日期。之后,如果您确实想对没有破折号的日期执行List和某些String的操作,则需要执行一些集合操作。这可以帮到您很多。

startDate.datesUntil(endDate).collect(Collectors.toList()).asScala.map(date => date.toString)

List[String] = ArrayBuffer(2020-01-01,2020-01-02,2020-01-03,...).toList
,

您可以执行以下操作:

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,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",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);

        return Stream.iterate(startDate,date -> date.plusDays(1))
                .limit(ChronoUnit.DAYS.between(startDate,endDate.plusDays(1)))
                .map(date -> date.format(formatter))
                .collect(Collectors.toList());
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。