使用 Scala 从给定月份获取前 12 个月的月份结束日期

时间:2021-05-23 21:22:33

标签: scala scala-collections

我有一个用例可以从给定日期获取过去 12 个月的结束日期。

例如,如果我将输入设为 ('2021-04-23'),则输出应为:

output1 = ('2021-04-30', '2021-03-31', '2021-02-28', '2021-01-31', '2020-12-31', ' 2020-11-30'、'2020-10-31'、'2020-09-30'、'2020-08-31'、'2020-07-31'、'2020-06-30'、'2020- 05-31', '2020-04-30')

output2=('2021-04-01','2021-03-01','2021-02-01','2021-01-01','2020-12-01',' 2020-11-01'、'2020-10-01'、'2020-09-01'、'2020-08-01'、'2020-07-01'、'2020-06-01'、'2020- 05-01','2020-04-01')

我有代码片段

import java.time.format.DateTimeFormatter

val monthDate = DateTimeFormatter.ofPattern("yyyy-MM")
val start = YearMonth.parse("2021-04", monthDate
val lastTwelveMonths=(0 to 12).map(x => start.minusMonths(x).format(monthDate)).toList

从当前月份返回过去 12 个月,任何人都可以提供包含前 12 个月结束日期的解决方案。谢谢

1 个答案:

答案 0 :(得分:4)

您可以根据需要使用 java.time.LocalDatewithDayOfMonth()

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

val dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd")
val inputDate = LocalDate.parse("2021-04-23")

(0 to 12).map{ n =>
  inputDate.minusMonths(n).withDayOfMonth(1).format(dateFormat)
}
// Vector(2021-04-01, 2021-03-01, 2021-02-01, 2021-01-01, 2020-12-01, 2020-11-01, 2020-10-01, 2020-09-01, 2020-08-01, 2020-07-01, 2020-06-01, 2020-05-01, 2020-04-01)

(0 to 12).map{ n => 
  val prevDate = inputDate.minusMonths(n)
  prevDate.withDayOfMonth(prevDate.lengthOfMonth).format(dateFormat)
}
// Vector(2021-04-30, 2021-03-31, 2021-02-28, 2021-01-31, 2020-12-31, 2020-11-30, 2020-10-31, 2020-09-30, 2020-08-31, 2020-07-31, 2020-06-30, 2020-05-31, 2020-04-30)