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

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()}" />

hope this comes handy


Where Am I?

You are currently viewing the archives for January, 2013 at Dinesh Simk.