如何使用javascript从托管bean显示计时器?

时间:2013-10-13 21:41:10

标签: java javascript jsf managed-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>

注意,我想在这里做的是完全依赖服务器来使用和显示时间而不是取决于客户端,如果还有其他方法可以告诉我这个问题

1 个答案:

答案 0 :(得分:1)

如何将其转换为时间戳并从中创建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>