My Android app accepts a date as a String in the format dd-MMM-yyyy
(e.g. 12-JAN-1992
). I am trying to convert this String to the format that is required by SQLite for its DATE type, i.e. yyyy-mm-dd
(e.g. 1992-01-12
). How can I accomplish that?
My code below is inefficient and it doesn't work (I end up getting a DATE in dd-MMM-yyyy
format and the MMM
part somehow changes):
public static Date convertInputBirth(String dateOfBirthStr) {
DateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
Date dateOfBirth;
try {
dateOfBirth = df.parse(dateOfBirthStr);
DateFormat DBdf = new SimpleDateFormat("yyyy-mm-dd");
String DBdateStr = DBdf.format(dateOfBirth);
dateOfBirth = DBdf.parse(DBdateStr);
return dateOfBirth;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/* ... Right before INSERTing to DB ... */
Format formatter = new SimpleDateFormat("yyyy-mm-dd");
Date d = convertInputBirth(input_from_user);
String date = (d != null) ? formatter.format(d) : null
/* INSERT date to a record ... */
Aucun commentaire:
Enregistrer un commentaire