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

JSF how to iterate over map using ui:repeat

2011/07/07 § 3 Comments

private Map<String, ArrayList<Person>> myMap = new TreeMap<String, ArrayList<Person>>();

This is how my map look like and i want to display both key and value pair on my html page. ui:repeat doesn’t handle the Sets or Maps by default so here is the work around how we can make it work.

Reguar getter seter Person Class

public class Person {
private String name = "";

private String gender = "";
private String address = "";

public Person(String name, String gender, String address) {
this.name = name;
this.gender = gender;
this.address = address;
}
..
..
}

Make a function that returns only the keys of map

private ArrayList<String> keys = new ArrayList<String>();
private void myKeys(){
for(String key: blocks.keySet()){
keys.add(key);
}
}

Call the Map on jsf page as follows,

<ui:repeat value="#{mapBean.keys}" var="key">
<ice:outputLabel value="#{key}"/>
<ui:repeat var="item" value="#{mapBean.myMap[key]}">
<ice:outputLabel value="#{item.name}"/>
<ice:outputLabel value="#{item.adress}"/>
</ui:repeat>
</ui:repeat>

Where Am I?

You are currently browsing the Java category at Dinesh Simk.