-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.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
sammy
  • 3
  • 2
  • Have you tried java.util.Date? – Gautham M Feb 13 '21 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 – sammy Feb 13 '21 at 16:06
  • Are you saying that you want the date to be stored in `yyyy-MM-dd` format in the database as well? – Gautham M Feb 13 '21 at 16:10
  • @GauthamM no I want it to be stored like the string "2020-02-22" – sammy Feb 13 '21 at 16:22
  • @GauthamM the format adds other information which I don't want – sammy Feb 13 '21 at 16:23
  • Which database are you using? Since the database stores this field as a `date` and not as a `string`, it would be stored in that way only. While retrieving the data from database you can convert it back to the desired `string` format using `SimpleDataFormat` – Gautham M Feb 13 '21 at 16:27
  • 1
    `myPreparedStatement.setObject( … , LocalDate.parse( "2020-02-22" ) ) ;` – Basil Bourque Feb 13 '21 at 22:08

1 Answers1

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);
}
Gautham M
  • 4,816
  • 3
  • 15
  • 37