Solved

Formatting elapsed time.

Posted on 2006-07-16
16
245 Views
Last Modified: 2010-03-31
All,

This object is supposed to time a process.
I create one before a process begins:

      ProcessTimer elapsed = new ProcessTimer();

...

then, when the [rocess is finished:

      log.info("Took: " + elapsed.format(elapsed.elapsed()));

The class looks like this:

public class ProcessTimer {
    // Creation of this object magically takes a note of the current time.
    private long start = System.currentTimeMillis();
    // Format for the time difference display.
    private static final SimpleDateFormat secondsFormat = new SimpleDateFormat("ss.SSS", Locale.UK);
    private static final SimpleDateFormat minutesFormat = new SimpleDateFormat("mm:ss.SSS", Locale.UK);
    private static final SimpleDateFormat hoursFormat = new SimpleDateFormat("hh:mm:ss.SSS", Locale.UK);

    /**
     * now
     *
     * @return Date
     */
    public long elapsed() {
      // What's the time now.
      return System.currentTimeMillis() - start;
    }

    /**
     * format
     *
     * @param elapsed Date
     * @return String
     */
    public String format(long elapsed) {
        Calendar c = new GregorianCalendar();
        c.setTimeInMillis(elapsed);
        String s = "";
        if ( c.get(c.HOUR) > 0 ) {
            s = hoursFormat.format(elapsed);
        } else if ( c.get(c.MINUTE) > 0 ) {
            s = minutesFormat.format(elapsed);
        } else {
            s = secondsFormat.format(elapsed);
        }        
        return s;
    }

}

Why does it ALWAYS think that HOURS > 0?

It produces output of the form:

Took: 01:00:00.000

Even for an 'instant' process.

Any ideas?

Paul
0
Comment
Question by:PaulCaswell
  • 7
  • 7
  • 2
16 Comments
 
LVL 13

Expert Comment

by:Webstorm
ID: 17118105
Maybe because of time-zone offset
0
 
LVL 14

Accepted Solution

by:
StillUnAware earned 125 total points
ID: 17118108
this will work:

        TimeZone tz = TimeZone.getDefault();
        tz.setRawOffset(0);
        Calendar c = new GregorianCalendar(tz);
0
 
LVL 13

Assisted Solution

by:Webstorm
Webstorm earned 125 total points
ID: 17118113
=> try:
   c.setTimeInMillis(elapsed-c.get(ZONE_OFFSET)-c.get(DST_OFFSET));
0
 
LVL 16

Author Comment

by:PaulCaswell
ID: 17118133
Hi Webstorm!

We meet again! :-)

>>c.setTimeInMillis(elapsed-c.get(c.ZONE_OFFSET)-c.get(c.DST_OFFSET));
That works perfectly! Why?????

Paul
0
 
LVL 13

Expert Comment

by:Webstorm
ID: 17118142
because getHour is localtime, and setTimeMillis use UTC
0
 
LVL 13

Expert Comment

by:Webstorm
ID: 17118146
StillUnAware's solution should work too : using UTC timeZone (00:00)
0
 
LVL 16

Author Comment

by:PaulCaswell
ID: 17118170
Ok, we know its a timezone issue and Webstorms solution will work but is perhaps 'clunky'. No offence meant Webstorm. :-)

I tried it like this:

public class ProcessTimer {
    // Creation of this object magically takes a note of the current time.
    private long start = System.currentTimeMillis();
    // Format for the time difference display.
    private static final SimpleDateFormat secondsFormat = new SimpleDateFormat("ss.SSS", Locale.UK);
    private static final SimpleDateFormat minutesFormat = new SimpleDateFormat("mm:ss.SSS", Locale.UK);
    private static final SimpleDateFormat hoursFormat = new SimpleDateFormat("hh:mm:ss.SSS", Locale.UK);

    // A zero-based time zone for time differences.
    static TimeZone zz = TimeZone.getDefault();

    /**
     * ProcessTimer
     */
    public ProcessTimer() {
        zz.setRawOffset(0);
     }


    /**
     * now
     *
     * @return Date
     */
    public long elapsed() {
      // What's the time now.
      return System.currentTimeMillis() - start;
    }

    /**
     * format
     *
     * @param elapsed Date
     * @return String
     */
    public String format(long elapsed) {
        Calendar c = new GregorianCalendar(zz);
   
        c.setTimeInMillis(elapsed);
        String s = "";
        if ( c.get(c.HOUR) > 0 ) {
            s = hoursFormat.format(elapsed);
        } else if ( c.get(c.MINUTE) > 0 ) {
            s = minutesFormat.format(elapsed);
        } else {
            s = secondsFormat.format(elapsed);
        }        
        return s;
    }

}

It still gives me the additional hour. What have I done wrong and why are java dates and times such a pain to work with?

Paul
0
 
LVL 14

Expert Comment

by:StillUnAware
ID: 17118190
This time it should work, for egzample my time zone is +2 hours, but the code You provided works and returned 00.093, when this was executed:

    public static void main(String[] args) throws Exception {
      ProcessTimer pt = new ProcessTimer();
      Thread.sleep(100);
      System.out.println(pt.format(pt.elapsed()));
    }
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 16

Author Comment

by:PaulCaswell
ID: 17118216
I'm in the UK. Its 9:57 pm right now local time. I get:

01:00:00.109

Any ideas?

Paul
0
 
LVL 16

Author Comment

by:PaulCaswell
ID: 17118262
I just noticed that DST_OFFSET et al are Java 5 features. I cant use those as the target VM will eventually be 1.4 only.

Paul
0
 
LVL 16

Author Comment

by:PaulCaswell
ID: 17118291
This works! And I understand why now too! Thanks for your help.

    // A zero-based time zone for time differences.
    static TimeZone zz = TimeZone.getTimeZone("GMT+0");


Paul
0
 
LVL 13

Expert Comment

by:Webstorm
ID: 17118296
Try:
 Calendar c = new GregorianCalendar(  new SimpleTimeZone(0,"UTC")  );
0
 
LVL 13

Expert Comment

by:Webstorm
ID: 17118309
>> I just noticed that DST_OFFSET et al are Java 5 features.
Not true, see API for 1.3.1  http://java.sun.com/j2se/1.3/docs/api/java/util/Calendar.html
0
 
LVL 16

Author Comment

by:PaulCaswell
ID: 17118385
Hi Webstorm,

>>Calendar c = new GregorianCalendar(  new SimpleTimeZone(0,"UTC")  );
Are you saying that

    static TimeZone zz = TimeZone.getTimeZone("GMT+0");

wont work in other time zones or did our posts cross?

>>Not true, see API for 1.3.1 ...
Ah! Oops! I'm still trying to get the hang of the JBuilder help system. :-(

Paul
0
 
LVL 13

Expert Comment

by:Webstorm
ID: 17118403
>> wont work in other time zones or did our posts cross?
posts cross, both should work.

:-)
0
 
LVL 16

Author Comment

by:PaulCaswell
ID: 17118407
Hi Webstorm,

Thanks! :-)

Paul
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

932 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now