How to convert Date to a particular format in android?

This is modified code that you should use:

String date="Mar 10, 2016 6:30:00 PM";
SimpleDateFormat spf=new SimpleDateFormat("MMM dd, yyyy hh:mm:ss aaa");
Date newDate=spf.parse(date);
spf= new SimpleDateFormat("dd MMM yyyy");
date = spf.format(newDate);
System.out.println(date);

Use hh for hours in order to get correct time.

Java 8 and later

Java 8 introduced new classes for time manipulation, so use following code in such cases:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy h:mm:ss a");
    LocalDateTime dateTime = LocalDateTime.parse(date, formatter);
    DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("dd MMM yyyy");
    System.out.println(dateTime.format(formatter2));

Use h for hour format, since in this case hour has only one digit.

Leave a Comment