One of the little known properties of date columns in XPages view panels is they’re actually browser locale aware. In other words, viewing a column of dates with a browser configured in the GB locale returns them with a dd/mm/yyyy format, and one in the US locale returns mm/dd/yyyy. This also extends to month names too, so for example ’13 Jul 2012′ in the British locale becomes ’13 juil. 2012′ in the French.

All very clever I’m sure you’ll agree, and anything that tailors data for the user’s preferred format (especially with such little work) is no bad thing. However it all starts to fall apart when you’re not displaying dates directly from the underlying view document, or are otherwise trying to be clever with some server-side JavaScript to calculate the date – either for the view panel’s column value, or maybe a date field on an XPage form. Instead you’ll find they’ll always be returned in the same locale as that of the server – the browser locale is disregarded.

This is a problem, because the locale-aware aspect of the XPage-rendered dates cannot be disabled, which introduces inconsistencies that could be catastrophic for your application if relying on the short date format only.

Rather than disabling this though, surely a better approach would be to make SSJS dates also locale aware instead… which is what this handy code snippet achieves. It works by passing in a date (this can be a NotesDateTime object, a Java date, or a string), converts it to a Java date if necessary, then uses DateFormat objects to perform the conversion. The important thing here is that it passes in the browser’s date format locale from the context XPage global object, which makes it browser locale aware.

function returnLocalShortDate(ndtDate) {
 // Receives NotesDateTime object, Java date or string; returns localised date string in XPages short date format
 if (@IsText(ndtDate)) { // string
 var jsDate = @TextToTime(ndtDate);
 } else if (ndtDate instanceof Date) { // Java date
 var jsDate:Date = ndtDate;
 } else if (@IsTime(ndtDate)) { // Notes date/time
 var jsDate:Date = ndtDate[0].toJavaDate();
 } else {
 // Now we have a Java date object, perform the conversion
 var strDate:String = java.text.DateFormat.getDateInstance(DateFormat.SHORT, context.getLocale()).format(jsDate);
 // Convert the year from 2 digit to 4 (XPages renders with 4 for short date)
 var strYear = jsDate.getFullYear();
 var strDateArray = strDate.split("/");
 strDate = ('0' + strDateArray[0]).slice(-2) + '/' + ('0' + strDateArray[1]).slice(-2) + '/' + strYear;

The code returns the date in the SHORT Java date format, however MEDIUM and LONG are also valid parameters if needed.