7

I want to format date from "MMM dd, yyyy HH:mm:ss a" to "MM.dd". I have following code

SimpleDateFormat ft = new SimpleDateFormat ("MMM dd, yyyy hh:mm:ss a");
t = ft.parse(date); //Date is Sep 16, 2015 10:34:23 AM and of type string.
ft.applyPattern("MM.dd"); 

but I am getting exception at t = ft.parse(date);

Please help

CupawnTae
  • 14,192
  • 3
  • 29
  • 60
Nishant
  • 1,635
  • 1
  • 11
  • 24

2 Answers2

13

Three possible explanations:

  1. your default locale is incompatible with the input date - e.g. it can't understand Sep as a month name
  2. there's something wrong with the input string, or
  3. t is the wrong type (e.g. java.sql.Date instead of java.util.Date, or some other type altogether), or is not declared.

You should include details of the exception in your question to figure out which it is, but here's a working example using basically your own code, with the addition of a specific Locale.

SimpleDateFormat ft = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a", Locale.US);
java.util.Date t=ft.parse("Sep 16, 2015 10:34:23 AM");
ft.applyPattern("MM.dd");
System.out.println(ft.format(t));

output:

09.16
CupawnTae
  • 14,192
  • 3
  • 29
  • 60
1
SimpleDateFormat sdf = new SimpleDateFormat("MM.dd", Locale.US);
System.out.println("Formatted Date: " + sdf.format(date));
rafaelasguerra
  • 2,685
  • 5
  • 24
  • 56