问题描述
例如,如果我将输入设为 ('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 个月结束日期的解决方案。谢谢
解决方法
您可以根据需要使用 java.time.LocalDate
的 withDayOfMonth()
:
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)