0

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?

user7379562
  • 349
  • 2
  • 6
  • 15

1 Answers1

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"))
Tanjin
  • 2,442
  • 1
  • 13
  • 20
  • Beautiful! In which cases it is not recommendable to use `LocalDate`? – user7379562 May 11 '17 at 16:51
  • When you need access to the timestamp, as a LocalDate does not contain that information. One can look into LocalDateTime, ZonedDateTime, or even Instant which are available in the java.time library. – Tanjin May 11 '17 at 16:59
  • There is one pending issue in this solution. How to use `new SimpleDateFormat("yyyy-MMM-dd")` with `LocalDate`? – user7379562 May 11 '17 at 17:15
  • Please see this: http://stackoverflow.com/questions/28177370/how-to-format-localdate-to-string – Tanjin May 11 '17 at 17:18
  • I tried it, but the problem is that I get error message `Cannot resolve symbol ofPattern`. – user7379562 May 11 '17 at 17:18
  • see updated answer - I was able to compile and get the dates printed successfully with that in the REPL – Tanjin May 11 '17 at 17:24
  • Now it's ideal.Thanks. – user7379562 May 11 '17 at 17:27
  • Maybe it will be interesting for you to answer this relevant question: http://stackoverflow.com/questions/43924922/how-to-automate-the-creation-of-string-elements-with-datetime – user7379562 May 11 '17 at 20:52