Scala-获取给定年份的所有月份和日期 [英] Scala - Get all months and days for a given year

查看:703
本文介绍了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)
    }

这篇关于Scala-获取给定年份的所有月份和日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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