问题
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?
回答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("-", "");
}
回答2:
Use replace method which will replace all ocurrences of '-'
for ''
:
private String convertDate(String dataPar) {
return dataPar.replace('-', '');
}
回答3:
Try replaceAll
(This ll replace -
with ""
means it ll remove -
) :
private String convertDate(String dataPar) {
if(dataPar.length() > 0){
return dataPar.replaceAll("-","");
}
return "NOVAL";
}
回答4:
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
回答5:
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 :)
回答6:
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;
}
来源:https://stackoverflow.com/questions/27314682/how-correctly-convert-this-string-using-substring-java-method