Reputation: 3
I am trying to simplify my life parsing logs and gathering times. I get a file with the log statements that all start with the time stamp in this format
16:08:39.660
I want to turn this string into a just a simple time that I can get the difference between the two in either seconds or milliseconds. I have been looking on here and it was suggested to use
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss.sss");
Date start = format.parse(startTimeString);
Date end = format.parse(endTimeString);
long difference = end.getTime() - start.getTime();
This however is giving me totally different times. For example, 16:08:39.660 was giving me 4:19. Because the times were wrong, it was giving me negative differences, which is impossible for my given context. How can I turn
16:08:39.660
16:08:52.452
into a difference of 12.792
?
Upvotes: 0
Views: 122
Reputation: 28279
You need SSS
for milliseconds, thy this:
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss.SSS");
A better approach is using java.time.LocalTime
and java.time.Duration
if you are working with java 8+, so you don't have to write the pattern:
LocalTime start = LocalTime.parse("16:08:39.660");
LocalTime end = LocalTime.parse("16:08:52.452");
Duration duration = Duration.between(start, end);
System.out.println(duration.toMillis()); // 12792
System.out.println(duration.toMillis() / 1000.00); // 12.792
System.out.println(duration.toSeconds()); // 12
Upvotes: 9