cruzerkk
cruzerkk

Reputation: 17

Convert date from string "yyyyddmm hh:mm:ss" to String "DD/MM/YYYY" in JAVA

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 .

Upvotes: 1

Views: 14706

Answers (2)

earthmover
earthmover

Reputation: 4525

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

Upvotes: 9

Ian Roberts
Ian Roberts

Reputation: 122414

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)

Upvotes: 0

Related Questions