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

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

提交回复
热议问题