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.