我目前正在研究如何将 Date 从托管 bean 传递到 javascript,然后将其显示为具有 format 的计时器"hh:mm:ss aa"
,我尝试过但它不起作用。
代码: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;
}
}
代码: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>
注意,我在这里要做的是完全依赖服务器来使用和显示时间,而不是依赖于客户端,如果这种情况有另一种方法,请告诉我。