如何计算功能样式中的'n'天间隔日期?

时间:2018-11-06 08:23:18

标签: scala functional-programming

我正在尝试计算从开始日期到结束日期的'n'天的间隔。函数签名将以start_date,end_date,interval作为参数,以返回包含给定间隔的开始,结束日期列表的地图。 >

Example: start_date:2018-01-01 , End_date : 2018-02-20 interval: 20

预期输出:

  

2018-01-01,2018-01-20(20天)

     

2018-01-21,2018-02-09(20天)

     

2018-02-09,2018-01-20(剩余)

我尝试用scala编写,但我不认为这是一种适当的功能性编写方式。

case class DateContainer(period: String, range: (LocalDate, LocalDate))

    def generateDates(startDate: String, endDate: String,interval:Int): Unit = {

      import java.time._
      var lstDDateContainer = List[DateContainer]()
      var start = LocalDate.parse(startDate)
      val end = LocalDate.parse(endDate)
      import java.time.temporal._
      var futureMonth = ChronoUnit.DAYS.addTo(start, interval)
      var i = 1
      while (end.isAfter(futureMonth)) {
        lstDDateContainer = DateContainer("P" + i, (start, futureMonth)):: lstDDateContainer
        start=futureMonth
        futureMonth = ChronoUnit.DAYS.addTo(futureMonth, interval)
        i += 1
      }
      lstDDateContainer= DateContainer("P" + i, (start, end))::lstDDateContainer
      lstDDateContainer.foreach(println)

    }

    generateDates("2018-01-01", "2018-02-20",20)

任何人都可以帮助我以实用的方式进行写作。

4 个答案:

答案 0 :(得分:1)

(未经测试)之类的东西

def dates(startDate: LocalDate, endDate: LocalDate, dayInterval: Int): List[(LocalDate, LocalDate, Int)] = {

  if(startDate.isAfter(endDate)) {
    Nil
  }
  else {

    val nextStart = startDate.plusDays(dayInterval)

    if(nextStart.isAfter(startDate)) {
      List((startDate, endDate, ChronoUnit.DAYS.between(startDate, endDate)))
    }
    else {
      (startDate, nextStart, dayInterval) :: dates(nextStart, endDate, dayInterval)
    }
  }
}

答案 1 :(得分:1)

我提供的解决方案产生的结果与问题中给出的结果略有不同,但可以轻松修改以得到所需的答案:

//Preliminaries
val fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd")
val startDate ="2018-01-01"
val endDate = "2018-02-21"
val interval = 20L   
val d1 = LocalDate.parse(startDate, fmt)
val d2 = LocalDate.parse(endDate, fmt)

//The main code
Stream.continually(interval)
  .scanLeft((d1, d1.minusDays(1), interval)) ((x,y) => {
    val finDate = x._2.plusDays(y)
    if(finDate.isAfter(d2))
      (x._2.plusDays(1), d2, ChronoUnit.DAYS.between(x._2, d2))
    else
      (x._2.plusDays(1), x._2.plusDays(y), y)
  }).takeWhile(d => d._3 > 0).drop(1).toList

结果:

(2018-01-01,2018-01-20,20)
(2018-01-21,2018-02-09,20)
(2018-02-10,2018-02-21,12)

这个想法是通过interval的流扫描一个三元组,并在没有剩余的日子时停止。

答案 2 :(得分:1)

使用java.time库生成日期,并使用Stream.iterate()生成间隔序列。

import java.time.LocalDate

def generateDates( startDate   :LocalDate
                 , endDate     :LocalDate
                 , dayInterval :Int ) :Unit = {
  val intervals =
    Stream.iterate((startDate, startDate plusDays dayInterval-1)){
      case (_,lastDate) => 
        val nextDate = lastDate plusDays dayInterval
        (lastDate plusDays 1, if (nextDate isAfter endDate) endDate 
                              else nextDate)
    }.takeWhile(_._1 isBefore endDate)
  println(intervals.mkString("\n"))
}

用法:

generateDates(LocalDate.parse("2018-01-01"), LocalDate.parse("2018-02-20"), 20)

// (2018-01-01,2018-01-20)
// (2018-01-21,2018-02-09)
// (2018-02-10,2018-02-20)

答案 3 :(得分:0)

如果您愿意使用Joda进行日期时间操作,这就是我使用的

import org.joda.time.{DateTime, Days}

// given from & to dates, find no of days elapsed in between (integer)
def getDaysInBetween(from: DateTime, to: DateTime): Int = Days.daysBetween(from, to).getDays

def getDateSegments(from: DateTime, to: DateTime, interval: Int): Seq[(DateTime, DateTime)] = {
    // no of days between from & to dates
    val days: Int = DateTimeUtils.getDaysInBetween(from, to) + 1

    // no of segments (date ranges) between to & from dates
    val segments: Int = days / interval

    // (remaining) no of days in last range
    val remainder: Int = days % interval

    // last date-range
    val remainderRanges: Seq[(DateTime, DateTime)] =
      if (remainder != 0) from -> from.plusDays(remainder - 1) :: Nil
      else Nil

    // all (remaining) date-ranges + last date-range
    (0 until segments).map { segment: Int =>
      to.minusDays(segment * interval + interval - 1) -> to.minusDays(segment * interval)
    } ++ remainderRanges
  }