【问题标题】:Scala - Get all months and days for a given yearScala - 获取给定年份的所有月份和日期
【发布时间】:2017-05-29 17:16:48
【问题描述】:

我需要创建一个函数,将给定年份的所有日期的序列作为字符串日期三倍(年、月、日)返回。

def allDaysForYear(year: String) = {
 ...// get every month and day for that $year

  }

那我就这样用:

for ((year, month, day) <- allDaysForYear("2017"))
        yield doSomethingElse(p(year), p(month), p(day))

在我的尝试中,我使用了 Calendar Object 和 Iterator[Calendar],但没有设法获得干净且小巧的代码。

这似乎并不复杂存档,也许有人对如何处理日期有更好的想法。

在 Scala 中执行此操作的最有效方法是什么?

谢谢

【问题讨论】:

    标签: scala date calendar


    【解决方案1】:

    我能够通过简单的理解和java.time.LocalDatejava.time.Year 做到这一点:

        import java.time.{LocalDate, Year}
    
        def allDaysForYear(year: String): List[(String, String, String)] = {
          val daysInYear = if(Year.of(year.toInt).isLeap) 366 else 365
          for {
            day <- (1 to daysInYear).toList
            localDate = LocalDate.ofYearDay(year.toInt, day)
            month = localDate.getMonthValue
            dayOfMonth = localDate.getDayOfMonth
          } yield (year, month.toString, dayOfMonth.toString)
        }
    

    【讨论】:

    • 这似乎不适用于闰年 - 例如2016 年,12 月 31 日缺失。
    • 查看更新代码(现在考虑闰年,需要添加另一个 java.time 导入)
    • 如果安装了 java 1.8,那会很糟糕,如果是较低版本怎么办?那样的话import java.time不可用,可以用什么代替?
    • 我看到您创建了另一个问题,指出了这一要求 - 请参阅我使用 Joda-Time 为该 Q 发布的答案。 Joda-Time 本质上是在 1.8 中创建之前的 java.time 包:stackoverflow.com/questions/44261011/…
    【解决方案2】:

    使用Lamma Date

    Date(2015, 1, 1) to Date(2015, 12, 131) foreach println 
    
    Date(2015,1,1)
    Date(2015,1,2)
    Date(2015,1,3)
    Date(2015,1,4)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-17
      • 2014-07-09
      • 2017-01-19
      • 1970-01-01
      • 2021-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多