如何计算功能样式中的'n'天间隔日期? [英] How to calculate 'n' days interval date in functional style?

查看:102
本文介绍了如何计算功能样式中的'n'天间隔日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to calculae the interval of 'n' days from start date to end date.Function signature would have start_date,end_date, interval as argument which return a map with list of start, end days of given intervals.

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

预期输出:

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

2018-01-01 , 2018-01-20 (20 days)

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

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

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

2018-02-09 , 2018-01-20 (remaining)

我试图用Scala编写代码,但我不认为这是一种适当的功能编写风格.

I tried to write in scala but i dont feel it's a proper functional style of writing.

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)

任何人都可以帮助我以实用的风格进行写作.

Could anyone help me to write in a functional style.

推荐答案

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

I offer a solution that produces a slightly different result than given in the question but could be easily modified to get the desired answer:

//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的流扫描一个三元组,并在没有剩余时间的情况下停止.

The idea is to scan a 3-tuple through a stream of interval and stop when no more days are remaining.

这篇关于如何计算功能样式中的'n'天间隔日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆