Date Format JAVA

Bishan picture Bishan · May 4, 2012 · Viewed 45k times · Source

I want to format 2012-05-04 00:00:00.0 to 04-MAY-2012. i have tried it with below steps.

    SimpleDateFormat sdf = new SimpleDateFormat(
            "yyyy-MM-dd 'T' HH:mm:ss.SSS");

    Date date;
    String dateformat = "";
    try {
        date = sdf.parse("2012-05-04 00:00:00.0");
        sdf.applyPattern("DD-MON-RR");
        dateformat = sdf.format(date);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

but i got below exception.

java.text.ParseException: Unparseable date: "2012-05-04 00:00:00.0"
    at java.text.DateFormat.parse(DateFormat.java:337)
    at com.am.test.Commit.main(Example.java:33)`

How could i do this?

Answer

Guillaume Polet picture Guillaume Polet · May 4, 2012

Here, this works:

  1. Remove the extra 'T' in your first pattern
  2. The second format is incorrect, it should be dd-MMM-yyyy.

Take a look at the Javadoc of SimpleDateFormat

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class temp2 {

    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

        Date date;
        String dateformat = "";
        try {
            date = sdf.parse("2012-05-04 00:00:00.0");
            sdf.applyPattern("dd-MMM-yyyy");
            dateformat = sdf.format(date);
            System.err.println(dateformat);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}