1

Can someone help me with this conversion ?

String dateTime="20140505 03:23:50"
DateFormat formatter=new SimpleDateFormat("DD/MM/yyyy");
String date=formatter.format(dateTime);

I want the output to be in this format - "DD/MM/YYYY" which should be a string .

cruzerkk
  • 17
  • 1
  • 2
  • 6

2 Answers2

8

You have to do this :

String dateTime="20140505 03:23:50";
DateFormat formatter=new SimpleDateFormat("yyyyMMdd HH:mm:ss");
Date date=formatter.parse(dateTime);
formatte.applyPattern("dd/MM/yyyy");
String dateStr = formatter.format(date);

First you have to convert your String to Date object using formatter.parse(string) based on your String pattern, and then you can change your Date to any String format by changing your SimpleDateFormat pattern.

Note: D: day in year and d: day in month, So use d instead of D.

You can use verity of patterns in java to format date as per your requirement. enter image description here

earthmover
  • 4,395
  • 10
  • 43
  • 74
  • i'm getting applyPattern(String) is undefined for type DateFormat. – cruzerkk May 06 '14 at 11:09
  • at your 2nd line `DateFormat formatter=new SimpleDateFormat("DD/MM/yyyy");`, use `SimpleDateFormat formatter=new SimpleDateFormat("DD/MM/yyyy");`, `DateFormat` is parent class of `SimpleDateFormat` and it has not have `applyPattern(String)` method. – earthmover May 06 '14 at 11:12
  • ...and don't forget to accept the ans if this **helped** you...:) – earthmover May 06 '14 at 11:16
0

If you're starting with a string (rather than a Date), you want a string as output, and the format is that consistent then the simplest answer would just be to use substring manipulation

dateTime.substring(6, 8) + "/" + dateTime.substring(4, 6) + "/"
      + dateTime.substring(0, 4)
Ian Roberts
  • 120,891
  • 16
  • 170
  • 183