Solved

Formatting elapsed time.

Posted on 2006-07-16
16
251 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
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

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

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
tomcat not starting 6 62
How  Can  I  resolve   this  Error "java.sql.SQLException: Invalid column index" 4 49
tomcat administrtor 12 58
iterator/ListIterator approach 17 39
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
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 will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

792 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