简体   繁体   English

如何使用substring()Java方法正确转换此String?

[英]How correctly convert this String using substring() Java method?

I have the following problem using the substring() Java function. 使用substring() Java函数时出现以下问题。

I have to do the following operation: 我必须执行以下操作:

I have a String representing a date having the following form: 2014-12-27 ( YEARS-MONTH-DAY ). 我有一个表示日期的字符串,其格式如下: 2014-12-27YEARS-MONTH-DAY )。

And I want convert it into a String like this: 20141227 (without the space betwen date component). 我想将其转换为如下字符串: 20141227 (日期组件之间没有空格)。

So I have implemented the following method that use the substring() method to achieve this task: 因此,我实现了以下使用substring()方法实现此任务的方法:

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? 我想念什么?

Use replace method which will replace all ocurrences of '-' for '' : 使用替换方法将替换所有出现的'-' ''

private String convertDate(String dataPar) {
    return dataPar.replace('-', '');
}

Try replaceAll (This ll replace - with "" means it ll remove - ) : 尝试replaceAll (这会取代 -""意味着它会删除-

private String convertDate(String dataPar) {
    if(dataPar.length() > 0){
       return dataPar.replaceAll("-","");
    }
    return "NOVAL";
}

A simple way would be to replace all the occurrences of - . 一个简单的方法是将替换所有出现的- If the separator could be different then maybe using SimpleDateFormat would be better. 如果分隔符可以不同,则使用SimpleDateFormat可能更好。

private String convertDate(String dataPar) {
    return datapar.replaceAll("-", "");
}

如果输入仅是日期,则可以使用SimpleDateFormat并使用类似yyMMdd的格式http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

I want you to just change the end indeces of the substring() methods as given below 我希望您仅更改substring()方法的结尾索引,如下所示

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

I tested, It works Fine as you requested :) 我测试了,按您的要求可以正常工作:)

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM