Pregunta

I am currently working on how to pass Date from managed bean to javascript, Then display it as a timer with format "hh:mm:ss aa", I have try but it doesn't work.

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, What I want to do here is to rely fully on the server to use and display the time and not depends on the client, If there is another approach for this situation tell me about it.

¿Fue útil?

Solución

What about converting it to a timestamp and creating a javascript date object from it

<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>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top