Java: How to convert a string (HH:MM:SS) to a dura

2019-01-23 14:52发布

i want to convert a string with a format of HH:MM:SS or MM:SS or SS into a datatype of Duration.

solution:

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

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

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

7条回答
Ridiculous、
2楼-- · 2019-01-23 15:11

I assume what you're ultimately trying to achieve is to compute the duration of the CD in seconds.

There are several ways to do this, but I think the most straightforward is to just split on : to get the hours, minutes, and seconds fields, then to compute the duration manually:

String timestampStr = "14:35:06";
String[] tokens = timestampStr.split(":");
int hours = Integer.parseInt(tokens[0]);
int minutes = Integer.parseInt(tokens[1]);
int seconds = Integer.parseInt(tokens[2]);
int duration = 3600 * hours + 60 * minutes + seconds;
查看更多
劫难
3楼-- · 2019-01-23 15:14
  1. Your myCdDuration is confusing. Do you want one Duration object equivalent to whatever was specified in the string, or a list of Duration objects where the first contains the hours, the second minutes etc?

  2. 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.

查看更多
放荡不羁爱自由
4楼-- · 2019-01-23 15:14

I have written this method in my utils class to parse various kind of duration strings. It is quite flexible :

public static int getSecondsFromFormattedDuration(String duration){
        if(duration==null)
            return 0;
        try{

            Pattern patternDuration = Pattern.compile("\\d+(?::\\d+){0,2}");

            int hours = 0;
            int minutes = 0;
            int seconds = 0;
            if(patternDuration.matcher(duration).matches()){
                String[] tokens = duration.split(":");
                if(tokens.length==1){
                    seconds = Integer.parseInt(tokens[0]);
                }else if(tokens.length == 2){
                    minutes = Integer.parseInt(tokens[0]);
                    seconds = Integer.parseInt(tokens[1]);
                }else{
                    hours = Integer.parseInt(tokens[0]);
                    minutes = Integer.parseInt(tokens[1]);
                    seconds = Integer.parseInt(tokens[2]);
                }

                return 3600 * hours + 60 * minutes + seconds;
            }else
                return 0;

        }catch (NumberFormatException ignored){
            return 0;
        }

}

This is how it parsed these durations :

"1"   -->  1
"10"  -->  10
"10:"   -->  0  (not a valid duration)
"10:07"   -->  607
"06:08"   -->  368
"7:22"   -->  442
":22"   -->  0  (not a valid duration)
"10:32:33"   -->  37953
"2:33:22"   -->  9202
"2:2:02"   -->  7322
"2:33:43:32"   -->  0  (not a valid duration)
"33ff"   -->  0  (not a valid duration)
"2d:33"   -->  0  (not a valid duration)
查看更多
劳资没心,怎么记你
5楼-- · 2019-01-23 15:19

I would suggest not using javax.xml.datatype.Duration, as its related to the XML Java API and it's confusing to use it if you are not dealing with XML. Moreover, it is an abstract class, and there's no non-abstract documented implementation of it in Java SE, so you'd have to either create your own non-abstract implementation or obtain an instance somehow (probably, playing with the XML API).

You manage time and dates in Java using the Date and Calendar classes. To convert Strings to Date/Calendar you use DateFormat or SimpleDateFormat. That will let you perform your duration arithmetic, although that's not 100% pretty.

Mansoor provides a way to do stuff manually using String manipulation and handling durations as numeric values- if you only do simple stuff, it might be more straightforward to do that.

If you have to perform more complex stuff, you might want to look into http://joda-time.sourceforge.net/

查看更多
\"骚年 ilove
6楼-- · 2019-01-23 15:20

Sample, Convert Current DateTime to Duration in Java 7.

DatatypeFactory.newInstance().newDuration(Calendar.getInstance().getTimeInMillis())

Output -

P48Y5M13DT19H59M24.658S

查看更多
唯我独甜
7楼-- · 2019-01-23 15:25

With Java 8 and Java.time.Duration you can do this given that the string is of the format HH:MM:SS or MM:SS or SS

Duration.ofSeconds(Arrays.stream(runtime.split(":"))
                  .mapToInt(n -> Integer.parseInt(n))
                  .reduce(0, (n, m) -> n * 60 + m));
查看更多
登录 后发表回答