Santhosh
Santhosh

Reputation: 33

How to subtract / add a day to date

I am trying to get today's date and find the List of dates for the previous 5 days in SCALA. For example, I have to subtract 3 days from the current date and add that resultant date to a List.

How can I do that?

import scala.collection.mutable.ArrayBuffer
val dateFormatter = new java.text.SimpleDateFormat("yyyy-MM-dd")
var today_date = new  java.util.Date()
var today = dateFormatter.format(today_date) 

var lst_5_days = ArrayBuffer[String]()
for(i <- 1 to 5)
{
  val prev_day= /* method to get`enter code here` date for previous day 
                 (today - i days) */
  lst_5_days +=prev_day
}

Upvotes: 1

Views: 2117

Answers (1)

Krzysztof Atłasik
Krzysztof Atłasik

Reputation: 22595

You shouldn't use java.util.Date nor java.text.SimpleDateFormat since when Java 8 was released they were replaced with newer, easier to use and immutable alternatives: java.time.LocalDate and java.time.format.DateTimeFormatter.

For example, LocalDate has a very convenient method minusDays, which you could use:

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

val now = LocalDate.now()
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")

val last5Days = (1 to 5).map(i => formatter.format(now.minusDays(i)))

Upvotes: 5

Related Questions