Home > Software design >  Kotlin convert string to date and take one day before
Kotlin convert string to date and take one day before

Time:10-28

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)

CodePudding user response:

If working with LocalDate is fine you could do

var date = LocalDate.parse("2021-05-06")
date = date.minusDays(1)

CodePudding user response:

val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
val date = LocalDate.parse("2021-05-06", formatter).minusDays(1)
println(date)

Output:

2021-05-05

CodePudding user response:

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

  • Related