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,231
  • 6
  • 22
  • 39
  • 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 – Alex.T 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 Beckers
  • 7,280
  • 2
  • 16
  • 21
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
  • 5,919
  • 8
  • 34
  • 35
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