Wednesday 15 June 2016

Date Formatting - Java - Android

The below code snippet will be most useful for the tyro's and intermediate developer to format their date values to the expected formats,  no need to worry about the format what we are getting from the JSON or XML values.  Just get the date value and make a input date format and define the separate string for expected output date format and also keep ready with the date value.

1
2
3
 String inputFormat = "EEE, dd MMM yyyy hh:mm:ss Z";
 String dateValue = "Wed, 18 Apr 2012 07:55:29 +0000";
 String outputFormat = "MMM dd,yyyy hh:mm a";

Pass those params to the below utility method to get a expected date format as string.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by rajendhiran.e on 6/15/2016.
 */
public class Utils
{
    public static String DateFormatter(String inputFormat, String outputFormat, String dateValue) throws ParseException {
        SimpleDateFormat dateformat = new SimpleDateFormat(inputFormat);
        Date newDate = dateformat.parse(dateValue);
        dateformat = new SimpleDateFormat(outputFormat);
        return dateformat.format(newDate);
    }
}

Code Snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
String Error="";
        try {
            String inputFormat = "EEE, dd MMM yyyy hh:mm:ss Z";
            String dateValue = "Wed, 18 Apr 2012 07:55:29 +0000";
            String outputFormat = "MMM dd,yyyy hh:mm a";
            Log.d("Date Content:", "Value: " + Utils.DateFormatter(inputFormat, outputFormat, dateValue));
        } catch (ParseException e) {
            Error="Parser - Date Formatter Error!";
        } catch (Exception e) {
            Error="Error "+e.getMessage();
        }
        Log.d("Err: ",Error);


No comments: