Solved

Formatting elapsed time.

Posted on 2006-07-16
16
253 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
What Is Transaction Monitoring and who needs it?

Synthetic Transaction Monitoring that you need for the day to day, which ensures your business website keeps running optimally, and that there is no downtime to impact your customer experience.

 
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

The Ultimate Checklist to Optimize Your Website

Websites are getting bigger and complicated by the day. Video, images, custom fonts are all great for showcasing your product/service. But the price to pay in terms of reduced page load times and ultimately, decreased sales, can lead to some difficult decisions about what to cut.

Question has a verified solution.

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

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
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…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

726 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