问题
I asked a question regarding this here. It works fine and is a nice solution, however I just realized that in some cases when java 1.8 is NOT installed import java.time is not available. I have java 1.7 and cannot update due many other issues.
after 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)
}
older java versions:
so, for instance using import java.util.{Calendar} how can the same issue be solved? -> Get all months and days for a given year
回答1:
If you can use Joda-Time, the following worked for me:
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)
}
来源:https://stackoverflow.com/questions/44261011/scala-get-list-of-days-and-months-for-a-selected-year