Java:如何将字符串(HH:MM:SS)转换为持续时间?
我想将格式为HH:MM:SS或MM:SS或SS的字符串转换为持续时间的数据类型。
i want to convert a string with a format of HH:MM:SS or MM:SS or SS into a datatype of Duration.
解决方案:
private ArrayList<Duration> myCdDuration = new ArrayList<Duration>();
private void convert(String aDuration) {
chooseNewDuration(stringToInt(splitDuration(aDuration))); //stringToInt() returns an int[] and splitDuration() returns a String[]
}
private void chooseNewDuration(int[] array) {
int elements = array.length;
switch (elements) {
case 1:
myCdDuration.add(newDuration(true, 0, 0, 0, 0, 0, array[0]));
break;
case 2:
myCdDuration.add(newDuration(true, 0, 0, 0, 0, array[0], array[1]));
break;
case 3:
myCdDuration.add(newDuration(true, 0, 0, 0, array[0], array[1],
array[2]));
break;
}
}
感谢您的帮助......任何更简单的方法那个? - >创建自己的Duration类:
thanks for help ... any easier way to do that ? -> create your own Duration class:
public class Duration {
private int intSongDuration;
private String printSongDuration;
public String getPrintSongDuration() {
return printSongDuration;
}
public void setPrintSongDuration(int songDuration) {
printSongDuration = intToStringDuration(songDuration);
}
public int getIntSongDuration() {
return intSongDuration;
}
public void setIntSongDuration(int songDuration) {
intSongDuration = songDuration;
}
public Duration(int songDuration) {
setIntSongDuration(songDuration);
}
将int值转换为字符串以进行输出/打印:
Converts the int value into a String for output/print:
private String intToStringDuration(int aDuration) {
String result = "";
int hours = 0, minutes = 0, seconds = 0;
hours = aDuration / 3600;
minutes = (aDuration - hours * 3600) / 60;
seconds = (aDuration - (hours * 3600 + minutes * 60));
result = String.format("%02d:%02d:%02d", hours, minutes, seconds);
return result;
}
-
您的
myCdDuration
令人困惑。您想要一个持续时间
对象等于字符串中指定的对象,还是持续时间$ c的列表$ c>第一个包含小时,第二个分钟等的对象?
Your
myCdDuration
is confusing. Do you want oneDuration
object equivalent to whatever was specified in the string, or a list ofDuration
objects where the first contains the hours, the second minutes etc?
你不能只是投一个字符串
进入其他一些对象。您应该将值解析为数字类型并使用 DataTypeFactory
构建持续时间
对象。
You can't just cast a String
into some other object. You should parse the value into an numeric type and use DataTypeFactory
to construct the Duration
object.