Displaying date and time in localized date pattern in Liferay (JSF)

2013/01/20 § Leave a comment

Different countries have different date and time formats, in USA it is represented as dd-mm-yyyy, in Sweden dates are official written in the format yyyy-mm-dd (you can read more about it in the following link http://en.wikipedia.org/wiki/Category:Date_and_time_representation_by_country). When developing a web application it can be common requirement that we want to display date and time in users localized pattern so that users won’t be confused. So here is the small trick how you can read users localized date pattern in JSF application in portlet.

Commonly in the JSF we can read the users local by calling following method


Locale browserLocale = FacesContext.getCurrentInstance().getViewRoot().getLocale();

but this also requires mapping of all the locales you want to support in faces-context.xml, if you know what locales you need to support then this will do the work, otherwise here is a small trick that will read the locale of user in Liferay and using that we can get the user’s localized date pattern.


public String readUsersDatepattern() {

HttpServletRequest req = (HttpServletRequest)(FacesContext
.getCurrentInstance().getExternalContext().getRequestMap()
 .get("com.liferay.portal.kernel.servlet.PortletServletRequest"));

Locale locale = req.getLocale();
 SimpleDateFormat dateFormat = (SimpleDateFormat) SimpleDateFormat
 .getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT, locale);

return dateFormat.toPattern();

}

and in the jsf page you can display is as


<h:outputText value="bean.timestamp">
<f:convertDateTime type="both" pattern="#{bean.datePattern()}" />
 </h:outputText>

hope this comes handy

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

What’s this?

You are currently reading Displaying date and time in localized date pattern in Liferay (JSF) at Dinesh Simk.

meta

%d bloggers like this: