Java 8 Time API: how to parse string of format “mm:ss” to Duration?

后端 未结 2 1795
没有蜡笔的小新
没有蜡笔的小新 2020-12-11 16:52

I tried to use DateTimeFormatter for it, but not found way. Duration.parse(\"\") only use special format.

相关标签:
2条回答
  • 2020-12-11 17:17

    IMHO, java 8 doesn't provide any facility for custom duration parsing.

    You should to do it "manually". For example (an efficient way) :

    import static java.lang.Integer.valueOf;
    
    import java.time.Duration;
    
    public class DurationParser {
        public static Duration parse(String input) {
            int colonIndex = input.indexOf(':');
            String mm = input.substring(0, colonIndex);
            String ss = input.substring(colonIndex + 1);
            return Duration.ofMinutes(valueOf(mm)).plusSeconds(valueOf(ss));
        }
    }
    
    0 讨论(0)
  • 2020-12-11 17:24

    You can parse the String yourself and reformat it into the format required by Duration

    String value = ... //mm:ss
    String[] fields = value.split(":");
    return Duration.parse(String.format("P%dM%sS", fields[0], fields[1]));
    
    0 讨论(0)
提交回复
热议问题