Create a list of String elements entitles accordin

2019-09-15 02:07发布

问题:

I want to create a list of String elements, each one having a date in its title:

data_2017_May_4
data_2017_May_3
data_2017_May_2

The important thing is how these dates are created. They should be created starting from current date till minus 2 days. If the current date is May 1 2017, then the result would be:

data_2017_May_1
data_2017_April_30
data_2017_April_29

The same logic is applied to the switch between years (December/January).

This is my code, but it does not consider the changes of months and years. Also it jumps in dates:

val formatter = new SimpleDateFormat("yyyy-MMM-dd")
val currDay = Calendar.getInstance

var list: List[String] = Nil
var day = null
var date: String = ""
for (i <- 0 to 2) {
  currDay.add(Calendar.DATE, -i)
  date = "data_"+formatter.format(currDay.getTime)
  list ::= date
}
println(list.mkString(","))

How to reach the objective?

回答1:

Can you use java.time.LocalDate? If so you can easily accomplish this:

import java.time.LocalDate
import java.time.format.DateTimeFormatter

val desiredFormat = DateTimeFormatter.ofPattern("yyyy-MMM-dd")

val now = LocalDate.now()
val dates = Set(now, now.minusDays(1), now.minusDays(2))

dates.map(_.format(desiredFormat))
  .foreach(date => println(s"data_$date"))


标签: scala