Scala - 获取所选年份的日期和月份列表

时间:2017-05-30 11:26:59

标签: scala calendar

我问了一个关于here的问题。它工作正常,是一个很好的解决方案,但我刚刚意识到,在某些情况下,当未安装java 1.8时import java.time不可用。我有java 1.7,因许多其他问题无法更新。

在java 1.8之后

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)
}

较旧的java版本:

所以,例如使用import java.util.{Calendar}如何解决同一问题? - &GT; 获取特定年份的所有月份和日期

1 个答案:

答案 0 :(得分:1)

如果您可以使用Joda-Time,以下内容适用于我:

import java.util.Calendar
import org.joda.time.{DateTime, LocalDate, DurationFieldType}

def allDaysForYear(year: String): List[(String, String, String)] = {
  val dateTime = new DateTime()
  val daysInYear = if(dateTime.withYear(year.toInt).year.isLeap) 366 else 365
  val calendar = Calendar.getInstance
  calendar.set(year.toInt, 0, 0)
  val ld = LocalDate.fromCalendarFields(calendar)
  for {
    day <- (1 to daysInYear).toList
    updatedLd = ld.withFieldAdded(DurationFieldType.days, day)
  } yield (year, updatedLd.getMonthOfYear.toString, updatedLd.getDayOfMonth.toString)
}