java.lang.IllegalArgumentException: Parse error -

2019-05-15 15:57发布

I am storing the current date in SQLite db using the variable CURRENT_DATE. I found that the date format used is yyyy-mm-dd in the same. I want to parse the date in the code but I get this error:

java.lang.IllegalArgumentException: Parse error: at 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);

At first, I am fetching the date from the database and storing it in a String variable (because date is stored as TEXT in SQLite) and then I am performing the above operations but I get the exception as parseError.

How can I solve this issue?

3条回答
放我归山
2楼-- · 2019-05-15 16:19

Could you please paste the value of dateStoredAsStringFetchedFromDB as returned from the database ? It's probable that the returned value does not match the yyyy-mm-dd format.

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

查看更多
啃猪蹄的小仙女
3楼-- · 2019-05-15 16:27

It seems your date format is wrong. You should take note that the uppercase M is used to represent months and the lowercase m is used for minutes. To solve this just change your yyyy-mm-dd to yyy-MM-dd.

Now if you want to change that format in the future you may 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 will display the initially stored date of 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 as well, just refer to the documentation Ankit has kindly linked for you.

查看更多
我想做一个坏孩纸
4楼-- · 2019-05-15 16:35

Format is wrong, try this:

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

Documentation.

查看更多
登录 后发表回答