Results 1 to 9 of 9
  1. #1
    Art Vandelay is offline Member
    Join Date
    May 2012
    Posts
    18
    Rep Power
    0

    Default Problem with time displaying as 01:00:00 instead of 00:00:00

    Hi all,

    I'm having an issue with the following timer program. It is probably a silly error, but I can't see it. When the following method is called :

    Java Code:
    // used via StopWatchTimer run() to set the elapsed time on the GUI
        public void setTimerTextLabel(String s) {
            time_elapsed.setText(s);
        }
    ...from within the second block of code below it ends up displaying the time after 1 second as "01:00:01" instead of "00:00:01" in the GUI.

    The entire code is handled by the following class:


    Java Code:
    package stopwatch;
    
    import java.text.SimpleDateFormat;
    import java.util.concurrent.TimeUnit;
    
    /*
     * This class is responsable for maintaining the time. It implements Runnable in
     * order to calculate the time.
     */
    public class StopWatchTimer implements Runnable {
    
        private StopWatchGUI swGui;
        private long starttime = 0;
        private long endtime = 0;
        private boolean isrunning = false;
        private long timepause = 0;
        private String timeresult;
        private long elapsed;
        private long secondspassed;
    
        /*
         * The constructor has a StopWatchGUI parameter. The object is used to
         * access the StopWatchGUI class in order to set the text of a label to the
         * correct time.
         */
        public StopWatchTimer(StopWatchGUI sw) {
            this.swGui = sw;
        }
        /*
         * The method run is executed when the thread is started from the
         * StopWatchGUI. It calculates the time that has spend and formats it. Then
         * it assigns the time to the label in the GUI.
         */
        @Override
        public void run() {
    
            try {
                while (isrunning) {
                    timeresult = (formatTime(startCounting()));
                    System.out.println(timeresult);
                    swGui.setTimerTextLabel(timeresult);
                    secondspassed = TimeUnit.SECONDS.convert(elapsed, TimeUnit.NANOSECONDS);
                    swGui.setTimeRemaing(secondspassed);
                    boolean played = swGui.testtimers(secondspassed);
    
                    if (played == true) {
                        Thread.sleep(4000);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace(System.out);
            }
        }
        /*
         * Returns the String variable timeresult.
         */
        public String getTimeResult() {
            return timeresult;
        }
    
        /*
         * This method is called when you want to start the timer. This needs to be
         * called before the thread.start() is called.
         */
        public void start() {
            if (isrunning == false) {
                starttime = System.nanoTime() - (timepause - starttime);
            } else {
                starttime = System.nanoTime();
            }
            isrunning = true;
        }
    
        /*
         * This method is called when you want to pause the timer.
         */
        public void pause() {
            isrunning = false;
            endtime = System.nanoTime();
            timepause = System.nanoTime();
        }
    
        /*
         * This method is called when you want to reset the timer.
         */
        public void reset() {
            starttime = 0;
            endtime = 0;
            timepause = 0;
            isrunning = false;
        }
        /*
         * This method is called inside the run method. It returns the elapsed time.
         * If the boolean isrunning is false. Then it will return the end time.
         */
        public long startCounting() {
            
            //elapsed = 0;
            if (isrunning) {
                elapsed = System.nanoTime() - starttime;
    
            } else {
                elapsed = endtime - starttime;
    
            }
            return elapsed / 1000000;
        }
    
        /*
         * This method is called inside the run method. It has a parameter that
         * represents the time and reformats that time. It then returns the
         * reformatted time.
         */
        public String formatTime(long elapsedTicks) {
    
            SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
            String time = formatter.format(elapsedTicks);
            return time;
        }
    }
    Any ideas?

    Thanks for any help.

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,598
    Rep Power
    5

    Default Re: Problem with time displaying as 01:00:00 instead of 00:00:00

    Where's the StopWatchGUI class? Where's main? The value "played?"

    Jim
    Last edited by jim829; 02-22-2013 at 05:42 PM.
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  3. #3
    Art Vandelay is offline Member
    Join Date
    May 2012
    Posts
    18
    Rep Power
    0

    Default Re: Problem with time displaying as 01:00:00 instead of 00:00:00

    Hi Jim, as I said... the main class is only :

    Java Code:
        public static void main(String args[]) {
            /*
             * Set the Nimbus look and feel
             */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /*
             * If Nimbus (introduced in Java SE 6) is not available, stay with the
             * default look and feel. For details see
             * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
    
    
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(StopWatchGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(StopWatchGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(StopWatchGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(StopWatchGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
    
            /*
             * Create and display the form
             */
            java.awt.EventQueue.invokeLater(new Runnable() {
    
                public void run() {
    
                    //StopWatchGUI sw = new StopWatchGUI();
                    new StopWatchGUI().setVisible(true);
                }
            });
        }
    That is... the issue with the '01:00:00' appearing must be in the code already provided.

    Thanks for having a look anyway.

  4. #4
    Art Vandelay is offline Member
    Join Date
    May 2012
    Posts
    18
    Rep Power
    0

    Default Re: Problem with time displaying as 01:00:00 instead of 00:00:00

    I'm pretty sure now the issue is with the SimpleDateFormat adding an hour due to time zone differences, but I'm still working on it. I could simply subtract an hour before displaying, but I'd rather it be usable all year without having to change the code every 6 months due to British summer time.

  5. #5
    Art Vandelay is offline Member
    Join Date
    May 2012
    Posts
    18
    Rep Power
    0

    Default Re: Problem with time displaying as 01:00:00 instead of 00:00:00

    For anyone else with the problem... it can be solved by changing to the following:

    Java Code:
            SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
            TimeZone tz = TimeZone.getTimeZone("GMT");
            formatter.setTimeZone(tz);
    ...the 01:00:00 now displays correctly as 00:00:00. However, I'm guessing that when BST starts I'll have to change the code.

    If anyone has solved...please post here! I tried Europe/London time but that didn't work.

  6. #6
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,006
    Rep Power
    20

    Default Re: Problem with time displaying as 01:00:00 instead of 00:00:00

    Don't use classes designed for handling dates.
    Look up Joda time if you want something that handles time periods.

    Or calculate the difference yourself.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  7. #7
    Art Vandelay is offline Member
    Join Date
    May 2012
    Posts
    18
    Rep Power
    0

    Default Re: Problem with time displaying as 01:00:00 instead of 00:00:00

    Hey Tolls, I agree that I should have avoided any methods that use Date-Time. However, I did not need to use Joda Time to accomplish this. All I did was delete the method

    Java Code:
    public String formatTime(long elapsedTicks) {
     
            SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
            String time = formatter.format(elapsedTicks);
            return time;
        }
    And replace it with a manual calculation.

    Java Code:
        // l is in nanoseconds
        private String convertLongToString(long l) {
           
            // convert to seconds
            long m = l / 1000;
            // retrieve hours, minutes, seconds
            long hours = m / 3600;
            long minutes = (m  % 3600) / 60;
            long seconds = m  % 60;
            // and get in a string format 00:00:00
            String time = twoDigitString(hours) + ":" + twoDigitString(minutes) + ":" + twoDigitString(seconds);
            return time;
        }
    
        private String twoDigitString(long number) {
            if (number == 0) {
                return "00";
            }
            if (number / 10 == 0) {
                return "0" + number;
            }
            return String.valueOf(number);
    Thus, my only import now is to TimeUnit.

  8. #8
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,515
    Blog Entries
    7
    Rep Power
    20

    Default Re: Problem with time displaying as 01:00:00 instead of 00:00:00

    You want to display a time duration; the SimpleDateFormat tries to display an 'absolute' time, given a 'where' (a time zone) and a 'when' (daylight saving time); the two don't match.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  9. #9
    Art Vandelay is offline Member
    Join Date
    May 2012
    Posts
    18
    Rep Power
    0

    Default Re: Problem with time displaying as 01:00:00 instead of 00:00:00

    Aye, I don't use SimpleDateFormat any more, that is the point of my previous post.

Similar Threads

  1. Displaying problem
    By lvuong in forum JavaServer Pages (JSP) and JSTL
    Replies: 0
    Last Post: 02-10-2011, 11:48 PM
  2. Question for Displaying time
    By siva_vs_siva in forum New To Java
    Replies: 5
    Last Post: 10-29-2010, 08:22 AM
  3. Regarding problem with displaying image in jsp
    By sandeepsai39 in forum New To Java
    Replies: 4
    Last Post: 10-04-2010, 04:23 PM
  4. Having problem displaying JTable
    By rmartinsaraujo in forum AWT / Swing
    Replies: 1
    Last Post: 05-20-2010, 03:34 PM
  5. Urgent-Imp-Displaying message with respect to system time
    By garinapavan in forum New To Java
    Replies: 1
    Last Post: 08-03-2007, 02:17 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •