-2

I have a

String s = "2020-02-22"`;

and I want to change it to Date so I can store it in my database which has has a column that does not accept anything but Date.

I tried using the LocalDate class but it's in API 26. Any help would be appreciated.

7
  • Have you tried java.util.Date? Commented Feb 13, 2021 at 15:41
  • @GauthamM yes I tried it with simpleDateFormat but it makes formatted date ,but I want my date to be just as my string Commented Feb 13, 2021 at 16:06
  • Are you saying that you want the date to be stored in yyyy-MM-dd format in the database as well? Commented Feb 13, 2021 at 16:10
  • @GauthamM no I want it to be stored like the string "2020-02-22" Commented Feb 13, 2021 at 16:22
  • 1
    myPreparedStatement.setObject( … , LocalDate.parse( "2020-02-22" ) ) ; Commented Feb 13, 2021 at 22:08

1 Answer 1

2

Assume that you fetch the date from database and pass it to the below method:

public String formatDate(Date date){
    SimpleDateFormat ff = new SimpleDateFormat("yyyy-MM-dd");           
    return ff.format(date);
}

EDIT : based on input from Basil, you could try Android Desugaring to make use of Java 8+ functionality without the need of minimum API level. This would allow the use of LocalDate instead of the old java.util.Date class. Using LocalDate you could parse a string to date as:

public LocalDate getDate(String dateString) {
    return LocalDate.parse(dateString);
}
Sign up to request clarification or add additional context in comments.

4 Comments

FYI: Those terrible classes were supplanted years ago by the modern java.time classes defined in JSR 310. Suggesting those legacy classes in 2021 is poor advice.
@BasilBourque Yes, but from the question, it seems like an older version is being used.
The latest Android tooling brings most of the java.time functionality to older versions of Android via “API desugaring”.
@BasilBourque Updated the answer based on comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.