0

I have the following problem using the substring() Java function.

I have to do the following operation:

I have a String representing a date having the following form: 2014-12-27 (YEARS-MONTH-DAY).

And I want convert it into a String like this: 20141227 (without the space betwen date component).

So I have implemented the following method that use the substring() method to achieve this task:

private String convertDate(String dataPar) {
    String convertedDate = dataPar.substring(0,3) + dataPar.substring(5,6) + dataPar.substring(8,9);
    return  convertedDate;
}

But it don't work well and return to me wrong conversion. Why? What am I missing?

AndreaNobili
  • 40,955
  • 107
  • 324
  • 596

6 Answers6

2

Use replace method which will replace all ocurrences of '-' for '':

private String convertDate(String dataPar) {
    return dataPar.replace('-', '');
}
DavidGSola
  • 697
  • 5
  • 17
1

Try replaceAll (This ll replace - with "" means it ll remove -) :

private String convertDate(String dataPar) {
    if(dataPar.length() > 0){
       return dataPar.replaceAll("-","");
    }
    return "NOVAL";
}
user3145373 ツ
  • 7,858
  • 6
  • 43
  • 62
1

A simple way would be to replace all the occurrences of -. If the separator could be different then maybe using SimpleDateFormat would be better.

private String convertDate(String dataPar) {
    return datapar.replaceAll("-", "");
}
James Fox
  • 691
  • 7
  • 24
0

If the input is only a date, you can use the SimpleDateFormat and use a format like yyMMdd http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Alex Barac
  • 632
  • 4
  • 12
0

I want you to just change the end indeces of the substring() methods as given below

String convertedDate = dataPar.substring(0,4) + dataPar.substring(5,7) + dataPar.substring(8,10);

I tested, It works Fine as you requested :)

rp3220
  • 60
  • 10
-1
private String convertDate(String dataPar) {
    final String year = dataPar.substring(0, 4);
    final String month = dataPar.substring(5, 7);
    final String day = dataPar.substring(8, 10);

    return year + month + day;
}
Smutje
  • 17,733
  • 4
  • 24
  • 41