Scala - Get list of days and months for a selected year

孤者浪人 提交于 2020-01-07 09:48:33

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!