Coder
Coder

Reputation: 3130

Android datetime parse issue

dateString: 2016-08-29T11:39:52.2133065

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    try {
      Date date = dateFormat.parse(dateString);
      return dateFormat.format(date);
    } catch (ParseException e) {
       Log.e(TAG, "Unable to parse date " + e);
    }

The string needs to be converted into 2016-08-29 11:39 but I am getting parse exception.

Upvotes: 0

Views: 455

Answers (2)

Mujammil Ahamed
Mujammil Ahamed

Reputation: 1494

Try this,remove T in your dateString,

                String dateString ="2016-08-29T11:39:52.2133065";
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                try {
                    Date date = dateFormat.parse(dateString);
                    dateFormat.format(date);
                    Log.e("Log",""+dateFormat.format(date));
                } catch (ParseException e)  {           
                        Log.e("GridActivity", "Unable to parse date " + e);
                }

Upvotes: 0

Mikael
Mikael

Reputation: 304

The format passed to the date formatter should correspond to the format of the string to be parsed. In the case of "2016-08-29T11:39:52.2133065" the date formatter should be:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");

You will also need a new formatter where you specify the output format:

SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

Use them like this:

Date date = dateFormat.parse(dateString);
return newFormat.format(date);

Upvotes: 1

Related Questions