5

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 milliseconds, 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

Nithin Michael
  • 2,166
  • 11
  • 32
  • 56
user706058
  • 415
  • 3
  • 11
  • 23

2 Answers2

3

because you convert the time difference into the date. In detail, this is exactly what it happens:

  1. SimpleDateFormat.format(long milliseconds) calculates the date : Unix Birth Time + milliseconds.
  2. This time is also adjusted with the time difference from GMT.
  3. 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.

belgther
  • 2,544
  • 17
  • 15
1

The execution time is off because the Date constructor takes a long specifying the number of milliseconds since 1970-01-01.

Daniel Lundmark
  • 2,370
  • 16
  • 11
  • 2
    Here is another stackoverflow answer with some really nice ideas! http://stackoverflow.com/questions/625433/how-to-convert-milliseconds-to-x-mins-x-seconds-in-java – Daniel Lundmark Jun 30 '11 at 20:23
  • Also, as a side note, I can really recommend the JodaTime API when dealing with dates in Java. It is really much nicer than the built-in Java Dates. http://joda-time.sourceforge.net/ – Daniel Lundmark Jun 30 '11 at 20:24
  • If you insist on using a date formatter, try this (insert your value for x): Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(Calendar.MILLISECOND, x); SimpleDateFormat sdf2 = new SimpleDateFormat("hh:mm:ss.SSS"); System.out.println(sdf2.format(cal.getTime())); – Steve Brisk Jun 30 '11 at 20:31
  • the Date is then converted to a Calendar in the SimpleDateFormat. The Calendar also takes TimeZones and Daylight Saving Time in consideration so I guess that's why you get 1 hour off (if your working europe somewhere) – Kennet Jun 30 '11 at 20:41
  • Thanks for the link Daniel, that helped – user706058 Jul 01 '11 at 07:27