Solved

Formatting elapsed time.

Posted on 2006-07-16
16
242 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
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
return in catch statement 1 40
json example 39 116
pairs challenge 5 46
java  and programming certification ? 4 65
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

743 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

15 Experts available now in Live!

Get 1:1 Help Now