Java – Date parsing yyyy-MM-dd’T’HH :mm:ss in Android

Date parsing yyyy-MM-dd’T’HH :mm:ss in Android… here is a solution to the problem.

Date parsing yyyy-MM-dd’T’HH :mm:ss in Android

My string date –> 2016-10-02T00:00:00.000Z. I just want to get the date from this string. I tried to parse with the encoding below, but it throws an error! My format is exactly the same as mentioned in the string. Is there an answer?

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss. SSSZ");
        try {
            Date myDate = sdf.parse( dateofJoining.replaceAll( "([0-9\\-T]+:[0-9]{2}:[0-9.+]+):([0-9]{2})", "$1$2" ) );
            System.out.println("Date only"+ myDate );
        } catch (ParseException e) {
            e.printStackTrace();
        }

I’m also tired of the code below

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");  
try {  
    Date date = format.parse(dtStart);  
    System.out.println(date);  
} catch (ParseException e) {  
     TODO Auto-generated catch block  
    e.printStackTrace();  
}

The error I get

java.text.ParseException: Unparseable date: "2016-10-02T00:00:00.000Z" (at offset 19)
05-12 00:18:36.613 4330-4330/com.vroom.riderb2b W/System.err:     at java.text.DateFormat.parse

Solution

Change the simple date format to use: yyyy-MM-dd'T'HH:mm:ss. SSSZ

In your code:

 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss. SSSZ");  
try {  
    Date date = format.parse(dtStart.replaceAll("Z$", "+0000"));  
    System.out.println(date);  
} catch (ParseException e) {  
     TODO Auto-generated catch block  
    e.printStackTrace();  
}

If you want to get date/mm/yy: from it

Use:

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yy");
 use UTC as timezone
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Log.i("DATE", sdf.format(date));   previous date object parsed

If you want the output format: hour:minute AM/PM

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(sdf.format(date));

Edit

A simpler option is to split the string into two parts, for example:

String dateString = "2016-10-02T00:00:00.000Z";
String[] separated = dateString.split("T");
separated[0];  this will contain "2016-10-02"
separated[1];  this will contain "00:00:00.000Z"

Related Problems and Solutions