Solved

Formatting elapsed time.

Posted on 2006-07-16
16
252 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 
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

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

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

Suggested Solutions

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
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…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
The viewer will learn how to implement Singleton Design Pattern in Java.

730 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