I have a String 00:01:30.500
which is equivalent to 90500
milliseconds. I tried using SimpleDateFormat
which give milliseconds including current date. I just need that String representation to milliseconds. Do I have to write custom method, which will split and calculate milliseconds? or Is there any other way to do this? Thanks.
I have tried as follows:
String startAfter = "00:01:30.555";
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SSS");
Date date = dateFormat.parse(startAfter);
System.out.println(date.getTime());
If you want to parse the format yourself you could do it easily with a regex such as
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.
You can use
SimpleDateFormat
to do it. You just have to know 2 things..getTime()
returns the number of milliseconds since 1970-01-01 00:00:00 UTC.Using JODA:
If you want to use
SimpleDateFormat
, you could write: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.