Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

date

android

My string date --> 2016-10-02T00:00:00.000Z. I want to get only date from this string. I tried to parse through below coding but it throws me error! I have exactly the same format as mentioned in the string. Any answers?

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 also tired below code,

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 which 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
like image 920
KarthikKPN Avatar asked Dec 18 '22 07:12

KarthikKPN


1 Answers

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 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

More easier option is to split the string in two parts like:

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"
like image 109
rafsanahmad007 Avatar answered Dec 28 '22 07:12

rafsanahmad007