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

后端 未结 4 1317
天命终不由人
天命终不由人 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:27

    Using JODA:

    PeriodFormatter periodFormat = new PeriodFormatterBuilder()
      .minimumParsedDigits(2)
      .appendHour() // 2 digits minimum
      .appendSeparator(":")
      .minimumParsedDigits(2)
      .appendMinute() // 2 digits minimum
      .appendSeparator(":")
      .minimumParsedDigits(2)
      .appendSecond()
      .appendSeparator(".")
      .appendMillis3Digit()
      .toFormatter();
    Period result = Period.parse(string, periodFormat);
    return result.toStandardDuration().getMillis();
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-28 10:44

    You can use SimpleDateFormat to do it. You just have to know 2 things.

    1. All dates are internally represented in UTC
    2. .getTime() returns the number of milliseconds since 1970-01-01 00:00:00 UTC.
    package se.wederbrand.milliseconds;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.TimeZone;
    
    public class Main {        
        public static void main(String[] args) throws Exception {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    
            String inputString = "00:01:30.500";
    
            Date date = sdf.parse("1970-01-01 " + inputString);
            System.out.println("in milliseconds: " + date.getTime());        
        }
    }
    
    0 讨论(0)
  • 2020-11-28 10:47

    If you want to use SimpleDateFormat, you could write:

    private final SimpleDateFormat sdf =
        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        { sdf.setTimeZone(TimeZone.getTimeZone("GMT")); }
    
    private long parseTimeToMillis(final String time) throws ParseException
        { return sdf.parse("1970-01-01 " + time).getTime(); }
    

    But a custom method would be much more efficient. SimpleDateFormat, because of all its calendar support, time-zone support, daylight-savings-time support, and so on, is pretty slow. The slowness is worth it if you actually need some of those features, but since you don't, it might not be. (It depends how often you're calling this method, and whether efficiency is a concern for your application.)

    Also, SimpleDateFormat is non-thread-safe, which is sometimes a pain. (Without knowing anything about your application, I can't guess whether that matters.)

    Personally, I'd probably write a custom method.

    0 讨论(0)
提交回复
热议问题