在 Spark Scala 中,我尝试创建一个列,其中包含开始日期和结束日期(含)之间的每月日期数组。
例如,如果我们有 2018-02-07 和 2018-04-28,则数组应包含 [2018-02-01, 2018-03-01, 2018-04-01]。
除了每月版本之外,我还想创建一个季度版本,即[2018-1, 2018-2]。
输入数据示例:
id startDate endDate
1_1 2018-02-07 2018-04-28
1_2 2018-05-06 2018-05-31
2_1 2017-04-13 2017-04-14
预期(每月)输出 1:
id startDate endDate dateRange
1_1 2018-02-07 2018-04-28 [2018-02-01, 2018-03-01, 2018-04-01]
1_1 2018-05-06 2018-05-31 [2018-05-01]
2_1 2017-04-13 2017-04-14 [2017-04-01]
最终预期(每月)产出2:
id Date
1_1 2018-02-01
1_1 2018-03-01
1_1 2018-04-01
1_2 2018-05-01
2_1 2017-04-01
我有 Spark 2.1.0.167、Scala 2.10.6 和 JavaHotSpot 1.8.0_172。
我试图在这里实现类似(日级)问题的几个答案,但我正在努力让每月/每季度的版本发挥作用。
下面的代码从 start 和 endDate 创建一个数组并将其分解。但是,我需要分解一个包含其间所有每月(季度)日期的列。
val df1 = df.select($"id", $"startDate", $"endDate").
// This just creates an array of start and end Date
withColumn("start_end_array"), array($"startDate", $"endDate").
withColumn("start_end_array"), explode($"start_end_array"))
感谢您提供任何线索。
最佳答案
case class MyData(id: String, startDate: String, endDate: String, list: List[String])
val inputData = Seq(("1_1", "2018-02-07", "2018-04-28"), ("1_2", "2018-05-06", "2018-05-31"), ("2_2", "2017-04-13", "2017-04-14"))
inputData.map(x => {
import java.time.temporal._
import java.time._
val startDate = LocalDate.parse(x._2)
val endDate = LocalDate.parse(x._3)
val diff = ChronoUnit.MONTHS.between(startDate, endDate)
var result = List[String]();
for (index <- 0 to diff.toInt) {
result = (startDate.getYear + "-" + (startDate.getMonth.getValue + index) + "-01") :: result
}
new MyData(x._1, x._2, x._3, result)
}).foreach(println)
关于java - 在 Scala 中,如何创建开始日期和结束日期之间的每月日期的日期数组列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58509728/