Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...