1

I am using the following to parse a string to date. However I get an Unparseable date exception. This is the code

String dateString="2018-09-20T11:44:48.000Z";//MYSQL timestamp from server
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy'T'HH:mm:ss.S'Z'");
Date convertedDate = new Date();
try {
  convertedDate = dateFormat.parse(dateString); //error here
  textTime.setReferenceTime(convertedDate.getTime());
} catch (ParseException e) {
  e.printStackTrace();
}
2
  • (1) Don’t get a string from MySQL, get an Instant, LocalDateTime or Timestamp, whichever works. (2) Consider avoiding the SimpleDateFormat class, it’s long outdated and notoriously troublesome. If java.time, the modern Java date and time API, isn’t built into your Android version, consider the ThreeTenABP library, the backport of java.time for Android. Commented Sep 20, 2018 at 14:20
  • Also don’t parse the Z in the date string as a literal (in single quotes). It’s a UTC offset and needs to be parsed as such. Otherwise SimpleDateFormat will use the JVM’s time zone, leading to an incorrect point in time. Commented Sep 21, 2018 at 7:19

1 Answer 1

2

You should rectify your SimpleDateFormat.

   String dateString="2018-09-20T11:44:48.000Z";

   SimpleDateFormat inputFormat     = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
   SimpleDateFormat outputFormat    = new SimpleDateFormat("MM/dd/yyyy'T'HH:mm:ss.S'Z'");

    Date   convertedDate    = null;
    String strOP            = null;

    try 
    {
        convertedDate = inputFormat.parse(dateString);
        strOP         = outputFormat.format(convertedDate);
        textTime.setReferenceTime(strOP);
    } 
    catch (ParseException e) 
    {
        e.printStackTrace();
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.