Format milliseconds to simpledate format
I'm facing a weird result when formatting milliseconds to a SimpleDate format:
Output is:
Start date time: 11/06/30 09:45:48:970
End date time: 11/06/30 09:45:52:831
Execution time: 01:00:03:861
Script:
long dateTimeStart = System.currentTimeMillis();
// some script execution here
long dateTimeEnd = System.currentTimeMillis();
"Start date time: " + GlobalUtilities.getDate(dateTimeStart, "yy/MM/dd hh:mm:ss:SSS");
"End date time: " + GlobalUtilities.getDate(dateTimeEnd, "yy/MM/dd hh:mm:ss:SSS");
"Execution time: " + GlobalUtilities.getDate((dateTimeEnd - dateTimeStart), "hh:mm:ss:SSS");
Method:
public static String getDate(long milliseco开发者_如何学Cnds, String format)
{
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(milliseconds);
}
Any idea why the execution time value is so off? It should be 00:00:03:861, not 01:00:03:861
Thanks
because you convert the time difference into the date. In detail, this is exactly what it happens:
- SimpleDateFormat.format(long milliseconds) calculates the date : Unix Birth Time + milliseconds.
- This time is also adjusted with the time difference from GMT.
- With these two informations, you get the weird result. To verify the information above, you can add day, month and year to the date.
Unfortunately, you can fix it by manually converting your time.
The execution time is off because the Date constructor takes a long specifying the number of milliseconds since 1970-01-01.
精彩评论