如何使用 substring() Java 方法正确转换此字符串? [英] How correctly convert this String using substring() Java method?
问题描述
我在使用 substring() Java 函数时遇到以下问题.
I have the following problem using the substring() Java function.
我必须做以下操作:
我有一个表示日期的字符串,格式如下:2014-12-27(YEARS-MONTH-DAY).
I have a String representing a date having the following form: 2014-12-27 (YEARS-MONTH-DAY).
我想把它转换成这样的字符串:20141227(没有日期组件之间的空格).
And I want convert it into a String like this: 20141227 (without the space betwen date component).
因此,我实现了以下使用 substring() 方法来完成此任务的方法:
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?
推荐答案
一个简单的方法是替换所有出现的 -
.如果分隔符可能不同,那么使用 SimpleDateFormat
可能会更好.
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("-", "");
}
这篇关于如何使用 substring() Java 方法正确转换此字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!