How to convert HH:mm:ss.SSS to milliseconds?

后端 未结 4 1319
天命终不由人
天命终不由人 2020-11-28 09:49

I have a String 00:01:30.500 which is equivalent to 90500 milliseconds. I tried using SimpleDateFormat which give milliseconds includi

4条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-28 10:28

    If you want to parse the format yourself you could do it easily with a regex such as

    private static Pattern pattern = Pattern.compile("(\\d{2}):(\\d{2}):(\\d{2}).(\\d{3})");
    
    public static long dateParseRegExp(String period) {
        Matcher matcher = pattern.matcher(period);
        if (matcher.matches()) {
            return Long.parseLong(matcher.group(1)) * 3600000L 
                + Long.parseLong(matcher.group(2)) * 60000 
                + Long.parseLong(matcher.group(3)) * 1000 
                + Long.parseLong(matcher.group(4)); 
        } else {
            throw new IllegalArgumentException("Invalid format " + period);
        }
    }
    

    However, this parsing is quite lenient and would accept 99:99:99.999 and just let the values overflow. This could be a drawback or a feature.

提交回复
热议问题