我能想出的唯一解决方案是向后走,手动检查这一天是否满足约束条件。这是一个通用的类,用于通过时间向后走以找到DateTime
满足某些约束的类:
class PreviousAdjuster(constraints: (DateTimeField, Int)*) extends WithAdjuster {
val unit = constraints.map(_._1.getBaseUnit).minBy(_.getDuration)
def doWithAdjustment(dateTime: DateTime): DateTime = {
var curr = dateTime
while (constraints.exists{case (field, value) => curr.get(field) != value}) {
curr = curr.minus(1, unit)
}
curr
}
}
with
然后我可以在 a 的方法中使用该调节器DateTime
:
val lastFridayThe13th = LocalDate.of(2012, 12, 12).`with`(new PreviousAdjuster(
ChronoField.DAY_OF_MONTH -> 13,
ChronoField.DAY_OF_WEEK -> DayOfWeek.FRIDAY.getValue))
println(lastFridayThe13th) // prints 2012-07-13
感觉应该有一种更有效的方法来做到这一点,因为限制意味着我们不必每天都走过,但我不知道如何实现......