Java.lang.IllegalArgumentException: Parse error - date format error?

I am storing the current date in a SQLite db using the CURRENT_DATE variable. I found that the date format is used yyyy-mm-dd

in the same way. I want to parse a date in code, but I am getting this error:

java.lang.IllegalArgumentException: parsing error: in java.util.Date.parseError

The code is shown below:

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");
    String formattedTaskDate = dateFormat.format(new Date(dateStoredAsStringFetchedFromDB));
    Date d = new Date(formattedTaskDate);

      

I first retrieve the date from the database and store it in a String variable (since the date is stored as TEXT in SQLite) and then I do the above operations, but I get the exception as a parseError .

How can I solve this problem?

+3


source to share


3 answers


Your date format seems to be wrong. You should take into account that upper case is M

used to represent months and lower case is M

used for several minutes. To fix this problem, just change your yyyy-mm-dd

to yyy-MM-dd

.

Now, if you want to change this format in the future, you can do so by doing something like this:



try {
     DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     Date input = inputFormat.parse(date);
     DateFormat outputFormat = new SimpleDateFormat(" EEEE MMMM-dd-yyyy ", Locale.ENGLISH);
     String finaldate = outputFormat.format(input);
            txtDate.setText(finaldate); <-- just an example of displaying the date 
     }catch (Exception ex) {
            Alerts.CatchError(getBaseContext(), ex.toString());
     }

      

This displays the originally saved date 2015-04-25 12:08:34

(yyyy-MM-dd HH: mm: ss) as Friday April-25-2015

. You can of course change this to your liking, just refer to the documentation Ankit has kindly linked for you.

+2


source


Format is not correct, try this:

String string = dateStoredAsStringFetchedFromDB;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse(string);

      



Documentation .

+1


source


Could you please insert the value dateStoredAsStringFetchedFromDB

as a return from the database? The return value is probably not in the yyyy-mm-dd format.

Also note that from the javadoc ( https://developer.android.com/reference/java/text/SimpleDateFormat.html ), the 'm' pattern stands for minutes, not month as you seem to expect.

0


source







All Articles