Is it possible to display the current date (today's) in JSF without using a backing bean?
I have the following code snippet , but it didn't work out.
<div class="leftSide">Today's date #{currentDate}</div>
or
<f:facet name="header">
<h:outputText value="Today's date" />
</f:facet>
<h:outputText value="#currentDate">
<f:convertDateTime pattern="MM/dd/yyyy" type="date" />
</h:outputText>
You could register an instance of java.util.Date
as a request scoped bean in faces-config.xml
.
<managed-bean>
<managed-bean-name>currentDate</managed-bean-name>
<managed-bean-class>java.util.Date</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
This way it's available as #{currentDate}
without the need for a custom backing bean class.
Update: the JSF utility library OmniFaces has such a bean already registered as #{now}
. So if you happen to use OmniFaces already, you can just make use of it directly.
<h:outputText value="#{now}">
<f:convertDateTime pattern="MM/dd/yyyy" type="date" />
</h:outputText>
In JSF you could use the implicit EL object session
that provides access to the current HttpSession. The HttpSession#getLastAccessedTime
time ...
... returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT, and marked by the time the container received the request.
So you could use the following code snippet in your facelet:
<h:outputText value="#{session.lastAccessedTime}">
<f:convertDateTime pattern="MM/dd/yyyy" type="date" />
</h:outputText>
This will be server time and may differ from client time with respect to different time zones.
But you could also use a javascript solution, as discussed here:
How do I get the current date in JavaScript?
Or you could do it using Omnifaces. I'm surprised BalusC hasn't told you about this solution (I think he's a great Omnifaces contributor). Maybe it's because using Omnifaces just to display a simple date in a page might be an overkill to some.
Anyway, if your project already uses Omnifaces, there are 2 managed beans exposed by default and one in particular that you may find handy. As per the tag documentation specifies, once Omnifaces is added to your project, you can use the #{now}
managed bean.
For instance, to set a Primefaces calendar's max date, I just wrote the following :
<p:calendar id="myCalendar" pattern="dd/MM/yyyy"
value="#{mybean.myDate}" maxdate="#{now}"/>
I guess the #{now}
managed bean can be used in many more situations, and probably yours as well.
If your project does not use Omnifaces yet, I suggest you look at their spec and see how helpful it could be for you.
For instance, I'm using their validateOrder
tag to make sure two dates are properly ordered.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With