Instructions for showing a timer on a webpage from a managed bean by utilizing JavaScript

I'm currently tackling the challenge of passing a Date from a managed bean to JavaScript and then displaying it as a timer in the format "hh:mm:ss aa". I've attempted it but so far, no luck.

Code: DateTimeManagmentMB.java (Managed Bean)

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import javax.annotation.PostConstruct;

@Named(value = "dateTimeManagmentMB")
@RequestScoped
public class DateTimeManagmentMB {

private String dateFormated = new String();
private Date date = new Date();

@PostConstruct
public void init() {
    SimpleDateFormat df = new SimpleDateFormat("hh:mm:ss aa");
    Calendar calendar = new GregorianCalendar();
    calendar.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));

    dateFormated = df.format(calendar.getTime());
    date = calendar.getTime();
}

public String getdateFormated() {
    return dateFormated;
}

public void setdateFormated(String dateFormated) {
    this.dateFormated = dateFormated;
}

public Date getDate() {
    return date;
}

public void setDate(Date date) {
    this.date = date;
}
}

Code: time.xhtml

<h:head>
    <script>
        var myVar = setInterval(function() {
            initTimer()
        }, 1000);

        function initTimer(date){
            document.getElementById("timer").innerHTML = date.toLocaleTimeString();
        }
    </script>
</h:head>
<h:body onload="initTimer(#{dateTimeManagmentMB.date});">
    <p id="timer"></p>
</h:body>

Note, My goal here is to solely rely on the server for using and displaying the time without depending on the client. If there's an alternative approach for this scenario, feel free to share.

Answer №1

Have you considered converting it into a timestamp and then creating a JavaScript date object from that?

<h:head>
    <script>
        var intervalDuration = 1000;
        var currentTime = new Date();
        var myVar = setInterval(function() {
            updateDisplay()
        }, intervalDuration );

        function updateDisplay() {
            currentTime = new Date(currentTime.getTime() + intervalDuration);
            document.getElementById("timer").innerHTML = currentTime;
        }
        function initTimer(time){
            currentTime = new Date(time);
        }
    </script>
</h:head>
<h:body onload="initTimer(#{dateTimeManagmentMB.date.time});">
    <p id="timer"></p>
</h:body>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Pass data from Angular to Java in order to apply LOGGER.info for logging needs

Initially, I had planned on simply using a console.log(); in the UI to handle logging, but it seems that our current logging system may not capture this information even though the UI is considered a service. I have been exploring various options and am u ...

Tips for effectively transmitting and managing a JSON object within an ASP.NET MVC controller

I am currently working on a project using ASP.NET MVC 4 and I'm facing an issue with sending a JSON object to a controller that is supposed to accept it. Here is the snippet of javascript and jQuery code I am using: var jsonObject = { "PlantShip ...

What is the best way to access props from a different file in a React application?

I am facing a challenge with my two files: EnhancedTableHead and OrderDialog. I need to access the props data from EnhancedTabledHead in my OrderDialog file. Is there a way to achieve this? Here is how my files are structured: //OrderDialog.jsx import ...

Executing a complex xpath using Java Script Executor in Selenium WebDriver

When working with a large grid and trying to find an element using XPath, I encountered some difficulties. The XPath used was: By.xpath("//div[contains(text(),'" +EnteredCompetitionName+ "')]/preceding- sibling::div[contains(concat(' &apo ...

Cleaning up HTML5 video content

I have been on the search for a solution that would allow me to "scrub" through HTML5 video. So far, I have not come across one and was considering developing my own. However, before diving into that process, I wanted to seek advice from the community here ...

Creating a cascading select menu based on the selected value of another select menu

I am in the process of creating a menu that displays two lists for regions: one <select> for selecting the region and another <select> for choosing from available municipalities within that region. I have set up a <form> and I utilize Jav ...

Grabbing only the button element using jQuery when a click event occurs

HEY THERE! I have a simple question that I need help with. To better explain the issue, I've included a small code snippet below. The problem I'm facing is related to grabbing the id of a button. Everything works fine except when I click on any ...

I'm confused as to why I am only receiving one object entry in my fetch response instead of the expected list of entries

Is there a way to fetch all entries as a response instead of just one value? For example, when the next value returned by the fetch is {"next":"/heretagium"}, I can replace "/hustengium" with "heretagium" to get th ...

Can a complete form be encapsulated within a single AngularJS directive?

While I have come across several instances of individuals utilizing a blend of HTML and directives to craft an AngularJS form (as seen here), my goal is to develop a self-contained widget. This widget would encompass all the necessary HTML for the form w ...

A method for selecting the checkbox in a mat-row that corresponds to a certain text with Selenium

I want to select the checkbox within a nested mat-row: <mat-row _ngcontent-dac-c252="" role="row" class="mat-row cdk-row ng-star-inserted"> <mat-cell _ngcontent-dac-c252="" role="cell" class=&quo ...

AngularJS Error: The method serviceName.functionName() is not a valid function

I am trying to implement a function that will go back when the cancel button is clicked. Here is the view code: <div ng-controller="goodCtrl"> <button class="btn" ng-click="cancel()">Cancel</button> </div> And here is the Jav ...

Custom positioning of Mui Snackbar in V5

I've been attempting to position a Snackbar in the top right corner with some customization for the top property, but I'm struggling to get it to display correctly. Here's what I've tried: import React from "react"; import { ...

How can I transfer a collection of JSON objects from JavaScript to C#?

Feeling a bit confused here. I have some Javascript code that will generate JSON data like the following: {type:"book" , author: "Lian", Publisher: "ABC"} {type:"Newspaper", author: "Noke"} This is just one example, I actually have more data than thi ...

Passing data in Angular 4 with eventEmitter across multiple layers of components

Struggling with a challenge in Angular and need some guidance. I am currently working with Angular 4 and here is the scenario: The app.component.html file contains a wrapper div that I want to be able to change its color by adding a class to it. However ...

How to Use jQuery Slice to Display the Top N Items from a Dropdown Menu

How can I display only the top 10 results from multiple UL lists in my navigation? The code snippet provided below currently works for the first list, but how can I extend this functionality to all of the lists? $(document).ready(function() { var elem ...

How can DataTables (JQuery) filter multiple columns using a text box with data stored in an array?

I've been attempting to create a multi-column filter similar to what's shown on this page () using an array containing all the data (referred to as 'my_array_data'). However, I'm facing issues with displaying those filter text boxe ...

How can I change a string into an Oracle.sql.Clob using Java?

I am currently in the process of coding a Java function within Oracle Database that generates a large amount of text. Can anyone provide guidance on how to convert a string to CLOB (oracle.sql.CLOB) in Java? What is the most direct way to accomplish this? ...

Encountered a SyntaxError: Unexpected token "e" while attempting to parse a JSON string

When I attempt to use JSON.parse in order to convert the string below into a JavaScript object, I encounter an "Uncaught SyntaxError: Unexpected token e" error. { "__type": "HRIS.oHRData, HRIES, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", ...

Having trouble starting a Java program in Eclipse?

Recently, I set up Eclipse (2020 version) and IBM ILOG CPLEX (12.6.9 version) on my Windows 10 system to run some existing Java code. The code utilizes the Java API of CPLEX, so I followed the instructions provided on CPLEX Official Page. These instruction ...

Give GetElementsByClassName a shot

Hey, have you tried using js ref_doc_getelementsbyClassName? "I keep getting the error message 'Uncaught TypeError: Cannot set property 'value' of null' " Check out this HTML code snippet: <input type="text" cla ...