如何使用 javascript 显示来自托管 Bean 的计时器



我目前正在研究如何将日期从托管bean传递到javascript,然后将其显示为格式为"hh:mm:ss aa"的计时器,我已经尝试过,但它不起作用。

代码: DateTimeManagmentMB.javaManaged 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;
}
}

代码: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>

注意,我在这里要做的是完全依靠服务器来使用和显示时间,而不依赖于客户端,如果有另一种方法可以解决这种情况,请告诉我。

将其转换为时间戳并从中创建javascript日期对象怎么样

<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>

相关内容

  • 没有找到相关文章

最新更新