0

I have a problem. I have a date in String f.eg "2021-05-06", and now i need to take one day before (2021-05-05). Here I'm making date from String but I cannot take one day before. Any tips?

val date = SimpleDateFormat("dd-MM-yyyy").parse(currentDate)
wenus
  • 1,345
  • 6
  • 24
  • 51
  • Does this answer your question? [How can I increment a date by one day in Java?](https://stackoverflow.com/questions/428918/how-can-i-increment-a-date-by-one-day-in-java). The same way a day is added here, you can also do minus – AlexT Oct 27 '21 at 08:57
  • Your date is in "yyyy-MM-dd" so parsing with a different format will not work.. – RobCo Oct 27 '21 at 08:57
  • @Alex.T this is not my question, but I will check it. – wenus Oct 27 '21 at 08:59
  • @RobCo ooo my mistake, thanks – wenus Oct 27 '21 at 08:59

3 Answers3

2

If working with LocalDate is fine you could do

var date = LocalDate.parse("2021-05-06")
date = date.minusDays(1)
Ivo
  • 18,659
  • 2
  • 23
  • 35
2
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
val date = LocalDate.parse("2021-05-06", formatter).minusDays(1)
println(date)

Output:

2021-05-05

Nikolai Shevchenko
  • 7,083
  • 8
  • 33
  • 42
1

By analogy with similar questions in Java (there was addition, but we can perform subtraction), we can get the following piece of code:

val date = LocalDate.parse(currentDate)
val newDate = date.minusDays(1)

First similar question

Second similar question

Roman Popov
  • 321
  • 5
  • 15