Reputation: 587
I am trying to generate the total time taken by my program to complete its job to print at the end of the program's execution. Following are the lines of code, I am using, to achieve this.
long startTime = System.currentTimeMillis(), endTime;
//actual programming logic
endTime = System.currentTimeMillis();
System.out.println((new SimpleDateFormat("HH:mm:ss.SSS").format(new Date(endTime).getTime() - new Date(startTime).getTime())));
The result here is 01:00:00.582 in place of 00:00:00.582. While I can imagine, this may be a very commonly faced issue, I tried my best to search with best keywords for this issue on web but nothing caught my eyes yet. Could someone throw some light on this?
Any responses are much aprpeciated. Thank you.
Upvotes: 0
Views: 820
Reputation: 587
I managed to produce what I am looking for. Here is the code for it, if someone needs it:
static String fn_Z_getTimeDifference(Long startTime, Long endTime)
{
long processTime = endTime - startTime;
long days = processTime / 86400000L;
processTime -= days * 86400000L;
long hours = processTime / 3600000L;
processTime -= hours * 3600000L;
long mins = processTime / 60000L;
processTime -= mins * 60000L;
long seconds = processTime / 1000L;
processTime -= seconds * 1000L;
long milliSeconds = processTime ;
return (Long.toString(hours)+ ":" + Long.toString(mins) + ":" + Long.toString(seconds) + ":" + Long.toString(milliSeconds)).toString();
}
Upvotes: 3
Reputation: 178293
When running code similar to your code:
long startTime = System.currentTimeMillis(), endTime;
try { Thread.sleep(582); } catch (InterruptedException ignored) {}
endTime = System.currentTimeMillis();
System.out.println((new SimpleDateFormat("HH:mm:ss.SSS").format(
new Date(endTime).getTime() - new Date(startTime).getTime())));
I get this output:
16:00:00.582
Showing the date reveals the time zone I'm in (UTC-8):
System.out.println((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(
new Date(endTime).getTime() - new Date(startTime).getTime())));
Output:
1969-12-31 16:00:00.582
You are constructing a Date
whose zero value is 00:00:00 January 1, 1970 UTC, but that is constructed in your own local time zone, which appears to have been one hour ahead of UTC on January 1, 1970.
Don't construct a Date
using a time interval.
Upvotes: 4
Reputation: 24895
You are formatting a number, because of wrapping and undwrapping the longs.
Try this
).format(new Date(endTime - startTime)));
or at the very least
").format(new Date(new Date(endTime).getTime() - new Date(startTime).getTime()))));
Upvotes: 0