user3652080 user3652080 - 10 days ago 6
Java Question

convert string to date and time as am/pm format

string : 2014-04-25 17:03:13


using SimpleDateFormat is enough to format?
or
otherwise i will shift to any new API?

Date date = new Date(string);
DateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd");
out.println( dateFormat.format (date));


My expected result is (India zone):

Date : 25-04-2014
Time : 05:03 PM

Answer

Remembering that Date objects have no inherent format, you need two DateFormat objects to produce the result you seek - one to parse and another to format:

String input = "2014-04-25 17:03:13";
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DateFormat outputFormat = new SimpleDateFormat("'Date : 'dd-MM-yyyy\n'Time : 'KK:mm a");
System.out.println(outputFormat.format(inputFormat.parse(input)));

Output:

Date : 25-04-2014
Time : 05:03 PM

Note the use of quoted sequences in the format, such a "'Date : '", which is treated as a literal within the format pattern.

To retrieve date and time from JSON and convert by using below code,

SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = fmt.parse(objLatestNews.getString("created_date"));

                        SimpleDateFormat fmtOut = new SimpleDateFormat("dd-MMM-yyyy hh:mm a");
                        Log.d("Date====>", fmtOut.format(date));
                        String finalDateTime = fmtOut.format(date);
                        latestNews.setDateTime(finalDateTime); 
Comments