gpt4 book ai didi

java - Java:如何将字符串(HH:MM:SS)转换为持续时间?

转载 作者:太空狗 更新时间:2023-10-29 22:37:19 24 4
gpt4 key购买 nike

我想将HH:MM:SS或MM:SS或SS格式的字符串转换为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类:
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值转换为输出/打印的字符串:
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令人困惑。您想要一个等效于字符串中指定的Duration对象,还是想要一个Duration对象列表,其中第一个包含小时数,第二个包含分钟数?
  • 您不能只将String转换为其他对象。您应该将值解析为数字类型,然后使用 DataTypeFactory 构造Duration对象。
  • 关于java - Java:如何将字符串(HH:MM:SS)转换为持续时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8257641/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com