Iterate over dates range (the scala way)

2020-05-24 05:20发布

Given a start and an end date I would like to iterate on it by day using a foreach, map or similar function. Something like

(DateTime.now to DateTime.now + 5.day by 1.day).foreach(println)

I am using https://github.com/nscala-time/nscala-time, but I get returned a joda Interval object if I use the syntax above, which I suspect is also not a range of dates, but a sort of range of milliseconds.

EDIT: The question is obsolete. As advised on the joda homepage, if you are using java 8 you should start with or migrate to java.time.

7条回答
smile是对你的礼貌
2楼-- · 2020-05-24 06:06
import java.util.{Calendar, Date}
import scala.annotation.tailrec

/** Gets date list between two dates
  *
  * @param startDate  Start date
  * @param endDate    End date
  * @return           List of dates from startDate to endDate
  */
def getDateRange(startDate: Date, endDate: Date): List[Date] = {
  @tailrec
  def addDate(acc: List[Date], startDate: Date, endDate: Date): List[Date] = {
    if (startDate.after(endDate)) acc
    else addDate(endDate :: acc, startDate, addDays(endDate, -1))
  }

  addDate(List(), startDate, endDate)
}

/** Adds a date offset to the given date
  *
  * @param date       ==> Date
  * @param amount     ==> Offset (can be negative)
  * @return           ==> New date
  */
def addDays(date: Date, amount: Int): Date = {
  val cal = Calendar.getInstance()
  cal.setTime(date)
  cal.add(Calendar.DATE, amount)
  cal.getTime
}
查看更多
登录 后发表回答