WISHY
WISHY

Reputation: 11999

Date conversion in java?

I have this date:2/23/2016 4:28:46 PM

String d="2/23/2016 4:28:46 PM";
Format formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
try {
    Date date = ((DateFormat) formatter).parse(d);
    formatter = new SimpleDateFormat("dd MMM HH:mm a");
    String notDate = formatter.format(date);
    holder.tvNotificationTime.setText(notDate);
    System.out.println(notDate);
} catch (ParseException e) {
    e.printStackTrace();
}

I want the output as

23 Feb 4:28 PM

But I get output as

23 Feb 04:28 am

What's wrong here?

Upvotes: 0

Views: 61

Answers (2)

M A
M A

Reputation: 72844

Use one H in the second DateFormat object:

formatter = new SimpleDateFormat("dd MMM h:mm a");

You also need to the AM/PM marker for the first formatter:

Format formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");

See this note from the Javadocs:

Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields.

Upvotes: 6

Pankaj Kumar Katiyar
Pankaj Kumar Katiyar

Reputation: 1494

How about this:

        Date date1 = new Date("2/23/2016 4:28:46 PM");
        SimpleDateFormat sdf = new SimpleDateFormat("dd MMM hh:mm:ss a");
        String formattedDate = sdf.format(date1);
        System.out.println("Formatted Date: "+formattedDate);

Upvotes: 1

Related Questions