Scala-获取给定年份的所有月份和日期

问题描述:

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

I need to create a function that return the sequence of all days for a given year as string date triples (year, month, day).

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

  }

然后我将以这种方式使用:

Then I will use in this way:

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

在我的尝试中,我使用了Calendar Object和Iterator [Calendar],但没有编写干净整洁的代码。

In my attempts I used Calendar Object and Iterator[Calendar], but did not managed to have a clean and small code.

归档似乎并不复杂,也许有人对如何处理日期有更好的了解。

This does not seem complicated to archive, perhaps someone has a better idea on how to handle dates.

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

What is the most efficient way to perform this in Scala?

感谢

我能够通过简单的理解以及 java.time.LocalDate java.time.Year

I was able to do this with a simple for comprehension and the java.time.LocalDate and java.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)
    }