How to convert Date to a particular format in android?

Viewed 71996

"Mar 10, 2016 6:30:00 PM" This is my date and I want to convert this into "10 Mar 2016". Can I use SimpleDateFormat in android. I am not getting the exact pattern to convert it. Please help and thanks in advance

String date="Mar 10, 2016 6:30:00 PM";
SimpleDateFormat spf=new SimpleDateFormat("Some Pattern for above date");
Date newDate=spf.format(date);
spf= new SimpleDateFormat("dd MMM yyyy");
String date = spf.format(newDate);

Will this steps work? If yes, can someone please give me a pattern of that format? Thanks in advance.

7 Answers

You can use following method for this problem. We simply need to pass Current date format, required date format and Date String.

private String changeDateFormat(String currentFormat,String requiredFormat,String dateString){
    String result="";
    if (Strings.isNullOrEmpty(dateString)){
        return result;
    }
    SimpleDateFormat formatterOld = new SimpleDateFormat(currentFormat, Locale.getDefault());
    SimpleDateFormat formatterNew = new SimpleDateFormat(requiredFormat, Locale.getDefault());
    Date date=null;
    try {
        date = formatterOld.parse(dateString);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    if (date != null) {
        result = formatterNew.format(date);
    }
    return result;
}

This method will return Date String in format you require. In your case method call will be:

String date = changeDateFormat("MMM dd, yyyy hh:mm:ss a","dd MMM yyyy","Mar 10, 2016 6:30:00 PM");

conversion from string to date and date to string

String deliveryDate="2018-09-04";                       
SimpleDateFormat dateFormatprev = new SimpleDateFormat("yyyy-MM-dd");
Date d = dateFormatprev.parse(deliveryDate);
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE dd MMM yyyy");
String changedDate = dateFormat.format(d);

You need to use SimpleDateFormat class to do the needful for you

String date = "Your input date"
 DateFormat originalFormat = new SimpleDateFormat("<Your Input format here>", Locale.US)
 DateFormat targetFormat = new SimpleDateFormat("<Your desired format here>", Locale.US)
 Date Fdate = originalFormat.parse(date)
 formattedDate = targetFormat.format(Fdate)
public static String formatDate(String fromFormat, String toFormat, String dateToFormat) {
    SimpleDateFormat inFormat = new SimpleDateFormat(fromFormat);
    Date date = null;
    try {
        date = inFormat.parse(dateToFormat);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    SimpleDateFormat outFormat = new SimpleDateFormat(toFormat);

    return outFormat.format(date);
}

Use: formatDate("dd-MM-yyyy", "EEEE, dd MMMM yyyy","26-07-2019");

Result: Friday, 26 July 2019

Related