0

I am trying to convert back a stored date/time string in the format of (MM dd, yyyy, HH:mm [AM/PM]), I followed this post to create the string date/time. My current code properly fetches the stored date time but when I try to parse it and display the Date object "d" I get a null output.

Java code:

public void loadExamData(Cursor cursor) {
    exam.setText(cursor.getString(1));
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
        Date d = sdf.parse(cursor.getString(2));
    } catch (ParseException ex) {
        Logger.getLogger(edit_exam_form.class.getName()).log(Level.SEVERE, null, ex);
    }

    location.setText(cursor.getString(3));
}
Community
  • 1
  • 1
nanjero echizen
  • 241
  • 1
  • 5
  • 14
  • An easier way might be to store a unix timestamp... that way, you can do whatever you want with it when you retrieve it. – Nerdy Bunz Sep 18 '16 at 04:13
  • 2
    SimpleDateFormat.parse() returns null on error. Are you sure the format string you're initializing sdf with matches the string from cursor? – Fletcher Johns Sep 18 '16 at 05:20

1 Answers1

0

First you have to parse the date string with the current pattern and then format it with your desired pattern.

For Example, if your current date string is like this [10/10/2016 14:30].

String curDate = "10/10/2016 14:30";
SimpleDateFormat curDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
SimpleDateFormat desiredDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
    Date date = curDateFormat.parse(curDate);
    String desiredDate = desiredDateFormat.format(date);
    // you can use this date string now
} catch (Exception e) {}