Iterate over dates range (the scala way)

后端 未结 7 1593
逝去的感伤
逝去的感伤 2021-02-04 10:26

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         


        
7条回答
  •  南方客
    南方客 (楼主)
    2021-02-04 11:21

    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
    }
    

提交回复
热议问题