VICKY-TSC
VICKY-TSC

Reputation: 415

I am trying to SimpleDateFormat date in java

I am trying to format a date by parsing it and then formating it but it is not working.

It is showing a parsing exception

public java.util.Date convertFormat(String DateTimeForm) 
                    throws ParseException {
 DateTimeForm="2012-06-01 10:00 PM";
 DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm aaa");
 java.util.Date FCDate = (java.util.Date) formatter.parse(DateTimeForm);

 return (java.util.Date) FCDate;

}

Upvotes: 0

Views: 388

Answers (2)

Gene
Gene

Reputation: 47020

This works fine on my machine. I didn't change anything important.

    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm aaa"); 
    Date date = null;
    try {
        date = formatter.parse("2012-06-01 10:00 PM");
    } catch (ParseException ex) {
        // Intentionally empty. Failed parse causes date == null. 
    }
    System.out.print(date);

prints

    Fri Jun 01 22:00:00 EDT 2012

The Java docs say the numerics are all locale-independent, but not the AM/PM. For example the code fails if you specify Locale.JAPAN in the formatter construction. Specify Local.US to guarantee AM/PM will always work.

Upvotes: 1

Raykud
Raykud

Reputation: 2484

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm aaa");
try {
    Date date = formatter.parse("2012-06-01 10:00 PM");
    System.out.println(date.toString());
    } catch (ParseException e) {
        e.printStackTrace();
    }

Didn't change anything and yet it works.

Fri Jun 01 22:00:00 CDT 2012

Upvotes: 1

Related Questions