Search code examples
javajavascriptjspclockrunnable

Displaying dynamic UTC clock time on JSP screen


I want to access the string variable in run() method and display the value on jsp screen. Please note that the value , which string variable in run() method holds, changes every 1 second as per the below code. Hence my requirement is to display the value on screen and change the value dynamically.

                              (OR)

To put it simple, all I am trying to display is the UTC clock time ,which changes every one second, on JSP screen.

public class Clock implements Runnable {

    JLabel jb;

//Constructor takes the clock JLabel
    public Clock(JLabel jb) {
        this.jb = jb;
    }


    public void run() {
        while (true) {
            try {
                //Thread sleeps & updates ever 1 second, so the clock changes every 1 second.
                jb.setText(timeNow());
                String dynaStr= timeNow();
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                System.out.println(ex);
            }
        }
    }
      public String timeNow() {
Calendar c = Calendar.getInstance();

    TimeZone z = c.getTimeZone();
    int offset = z.getRawOffset();
    if(z.inDaylightTime(new Date())){
        offset = offset + z.getDSTSavings();
    }
    int offsetHrs = offset / 1000 / 60 / 60;
    int offsetMins = offset / 1000 / 60 % 60;

    System.out.println("offset: " + offsetHrs);
    System.out.println("offset: " + offsetMins);

    c.add(Calendar.HOUR_OF_DAY, (-offsetHrs));
    c.add(Calendar.MINUTE, (-offsetMins));

    System.out.println("GMT Time: "+c.getTime());
    return c.getTime().toString();
}
}

Solution

  • Use javascript not java. An example is:

    var myVar=setInterval(function () {myTimer()}, 1000);
    function myTimer() {
        var date = new Date();
        document.getElementById("demo").innerHTML = date.toISOString();
    }
    

    demo being your div or whatever your using for display.

    Here is fully functional code just copy and paste into text document and change extension from txt to html or (jsp). Then double click to run in browser.

    <html>
    <head>
    <title></title>
    
    <script type="text/javascript">
    var myVar=setInterval(function () {myTimer()}, 1000);
    var counter = 0;
    function myTimer() {
        var date = new Date();
        document.getElementById("demo").innerHTML = date.toISOString();
    }
    </script>
    
    </head>
    <body>
       <span id="demo"></span>
    </body>
    </html>
    

    You can also use date.toUTCString() which will give you the same thing just different format.