0

I have a date String Mon Feb 8 00:00:00 UTC+0530 1954. I want to convert it into the format DD/MM/YYYY. The output is always 08/38/1954 or 09/39/1954.

I have used the following code.

SimpleDateFormat format = new SimpleDateFormat("MM/DD/YYYY", Locale.US);
System.out.println(format.format(new Date(dateStr)));
Tiny
  • 27,221
  • 105
  • 339
  • 599
Vinod
  • 3
  • 5

4 Answers4

3

DD in SimpleDateFormatis for the "Day in year", you want "Day in month", which is dd.

Also beware that YYYY is for "Week year", which depending on the calendar falls back to "Year", which is represented as yyyy. I suppose, you want yyyyanyways.

Martin C.
  • 12,140
  • 7
  • 40
  • 52
2

You need to use the parse() method to go from a String date to the defined SimpleDateFormat.

 SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
 Date date = format.parse(dateStr);
 System.out.println(format.format(date));
  • This will output the current date in the given format. He specifically wants to output the given date, which needs to be parsed first. – Martin C. Aug 08 '14 at 19:36
  • He has a very specific input string, your's will try to match it against the format pattern. – Martin C. Aug 08 '14 at 19:41
  • by using the above code i am getting the parse exception. but when i create new date object and format i am getting the correct output. why it is getting parser exception. – Vinod Aug 09 '14 at 06:14
2

Try this:

SimpleDateFormat frmt = new SimpleDateFormat("E MMM d HH:mm:ss zZ yyyy", Locale.US);
Date dateStr = frmt.parse("Mon Feb 8 00:00:00 UTC+0530 1954");
Sas
  • 2,473
  • 6
  • 30
  • 47
  • My answer was really unnecessary, but I like to think in some regex solution to things like this. It's was like to redesign the wheel. – daniel souza Aug 13 '14 at 17:43
0

D in SimpleDateformat stands for day in year where as d stands for day in month so replace DD with dd.

similary replace YYYY with yyyy

SparkOn
  • 8,806
  • 4
  • 29
  • 34