gpt4 book ai didi

scala - 填充日期元组数组

转载 作者:行者123 更新时间:2023-12-02 16:08:52 30 4
gpt4 key购买 nike

我正在尝试传递需要采用以下格式的日期范围列表。

val predicates =
Array(
“2021-05-16” → “2021-05-17”,
“2021-05-18” → “2021-05-19”,
“2021-05-20” → “2021-05-21”)

然后我使用 map 创建一系列条件,这些条件将传递给 jdbc 方法。

val predicates =
Array(
“2021-05-16” → “2021-05-17”,
“2021-05-18” → “2021-05-19”,
“2021-05-20” → “2021-05-21”
).map { case (start, end) =>
s"cast(NEW_DT as date) >= date ‘$start’ AND cast(NEW_DT as date) <= date ‘$end’"
}

该过程需要每天运行,我需要动态填充这些值,因为我无法使用硬编码方式。

需要帮助我如何从一个方法中返回这些值,该方法可以像上面那样生成递增的 start_date 和 end_date 元组。我有一个像下面这样的想法,但因为我是 scala 的新手,所以无法弄清楚。请帮忙

def predicateRange(start_date: String, end_date: String): Array[(String,String)] = {
// iterate over the date values and add + 1 to both start and end and return the tuple
}

最佳答案

这假设每个范围的持续时间都相同,并且每个日期范围都从前一个范围结束后的第二天开始。

import java.time.LocalDate
import java.time.format.DateTimeFormatter

def dateRanges(start: String
,rangeLen: Int
,ranges: Int): Array[(String,String)] = {
val startDate =
LocalDate.parse(start, DateTimeFormatter.ofPattern("yyyy-MM-dd"))
Array.iterate(startDate -> startDate.plusDays(rangeLen), ranges){
case (_, end) => end.plusDays(1) -> end.plusDays(rangeLen+1)
}.map{case (s,e) => (s.toString, e.toString)}
}

用法:

dateRanges("2021-05-16", 1, 3)
//res0: Array[(String, String)] = Array((2021-05-16,2021-05-17), (2021-05-18,2021-05-19), (2021-05-20,2021-05-21))

关于scala - 填充日期元组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68599723/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com