2

I have a following string which I have to split and replace with "/" on some condition**

String date = "20131105";

I want to change these string to "2013/11/05"

Edit:

I mean variable date must be String not Date data type

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
Rex
  • 77
  • 7

4 Answers4

12

Do like this

Date date = new SimpleDateFormat("yyyyMMdd").parse("20131105");
String formattedDate = new SimpleDateFormat("yyyy/MM/dd").format(date);
System.out.println(formattedDate);

Output

2013/11/05
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
3

Use the substring method.

date = date.substring(0, 4) + "/" + date.substring(4, 6) + "/" + date.substring(6, 8);
Sorter
  • 9,704
  • 6
  • 64
  • 74
3

try this

 String date = "20131105";
String date1=date.substring(0, 4);
String date2=date.substring(4,6);
String date3=date.substring(6,8);
System.out.println(date1+"/"+date2+"/"+date3);

output 2013/11/05

SpringLearner
  • 13,738
  • 20
  • 78
  • 116
2

See you have many logics .. you can use any one..

for example answer from prabhakaran which is

Date date = new SimpleDateFormat("yyyyMMdd").parse("20131105");
String formattedDate = new SimpleDateFormat("yyyy/MM/dd").format(date);
System.out.println(formattedDate);

here you can do one change like this

Date date = new SimpleDateFormat("yyyyMMdd").parse(StringVaribale);
String formattedDate = new SimpleDateFormat("yyyy/MM/dd").format(date);
System.out.println(formattedDate);

here you are converting to date and then converting back to string

Another one is you can take a substring and add "/" into your string in this logic you should take StringBuffer insteed of string. because this is having some extra feature.

Pankaj Goyal
  • 950
  • 9
  • 15