xPages: Date formatting.

Update: Mark pointed it out already in his comment but the format I used in the java class contained an error. Fixed it to be dd-MM-yyyy

A couple of days ago I came across the following blog post “Custom date field format in an XPage – mm/dd/yyyy“on Mark Roden’s blog. The blog is about changing the default date format of a a date/time field in xPages with find/replace of the eclipse client.

There where up to 73 changes made after the find/replace action. After I read the blogpost I remember I had the same issue on one of my xPage projects lately. In the design the format of the date was defined specifically. Since I didn’t want to have to change all date/time controls afterwards when the format didn’t seem to be correct anyway.  I decided to create a profile document in the database where these kind of settings where saved.

But how to use these settings within a date/time field? It’s actually straight forward. Please take a look at the following code snippet:


As you can see the pattern is somehow retrieved from the config.defaultdateformat property. For those who already have used managed beans before this should look familiar.

This piece of code actually tells the converter to use the dateformat specified in object found by the name config with the property DefaultDateFormat. Now If we take a look at the actual managed bean we see the following:

As you can see I defined a class called ‘configuration’ with a public get method ‘getDefaultDateFormat’. This method tries to open a profile document , read textfield inside this document and retrieves the value. If the value is not found a default value is returned just to be sure a correct pattern is defined. Finally when everything is done the profile document is being recycled.

The last piece of the puzzle is the faces-config file:

<?xml version="1.0" encoding="UTF-8"?> <managed-bean> <managed-bean-class>eu.jeroensomhorst.configuration</managed-bean-class> <managed-bean-scope>application</managed-bean-scope> <managed-bean-name>config</managed-bean-name> </managed-bean> <faces-config/>

The faces config defines how a certain java class is found in the system. The managed-bean-name property defines the global variabel under which we can access an instance of the object. In this case config. the scope and the class define at which scope the object is created ( application, session, view,request) and finally which class should be initiated.

This simple class can safe you a alot of hassle with default settings in your application. You only need to save the profile document again and when the cache is being invalided ( ie. the application scope isbeing destroyed ) the new values are available to the user.

I hope you enjoy this little explanation on how to use a managed bean to acces your settings easily without having to change upto 70 converters!