Change date string format in android

I am getting date string from SAX parsing like this: Wed, 18 Apr 2012 07:55:29 +0000

Now, I want this string as : Apr 18, 2012 01:25 PM

How can I do this?


Solution 1:

SimpleDateFormat format = new SimpleDateFormat("MMM dd,yyyy  hh:mm a");
String date = format.format(Date.parse("Your date string"));

UPDATE :-

As on, Date.parse("Your date string"); is deprecated.

String strCurrentDate = "Wed, 18 Apr 2012 07:55:29 +0000";
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss Z");
Date newDate = format.parse(strCurrentDate);

format = new SimpleDateFormat("MMM dd,yyyy hh:mm a");
String date = format.format(newDate);

Solution 2:

This will do it:

public static String formateDateFromstring(String inputFormat, String outputFormat, String inputDate){

    Date parsed = null;
    String outputDate = "";

    SimpleDateFormat df_input = new SimpleDateFormat(inputFormat, java.util.Locale.getDefault());
    SimpleDateFormat df_output = new SimpleDateFormat(outputFormat, java.util.Locale.getDefault());

    try {
        parsed = df_input.parse(inputDate);
        outputDate = df_output.format(parsed);

    } catch (ParseException e) { 
        LOGE(TAG, "ParseException - dateFormat");
    }

    return outputDate;

}

Example:

String date_before = "1970-01-01";
String date_after = formateDateFromstring("yyyy-MM-dd", "dd, MMM yyyy", date_before);

Output:

date_after = "01, Jan 1970";

Solution 3:

From oficial documentation, in the new API (18+) you should be implement this:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US);
String time=sdf.format(new Date());

Documentation: http://developer.android.com/reference/java/text/SimpleDateFormat.html

Solution 4:

The easiest solution is to use DateFormat's getter methods: The getDateTimeInstance DateFormat object formats date like that: Dec 31, 1969 4:00:00 PM, however there are those extra zeroes after 4:00

Date date = new Date();
String fDate = DateFormat.getDateTimeInstance().format(date);
System.out.println(fDate);