Thursday, April 8, 2010

XPages: Code snippet for date/string conversion

The SimpleDateFormat object is cached in the application scope due to performance/memory concerns (I have data tables generated from JSON with up to several thousand conversions).

Example usage:
String to date
DateConverter.stringToDate( '12.12.2001', 'dd.MM.yyyy' ) -> java.util.Date

Date to string
DateConverter.dateToString( @Now(), 'dd.MM.yyyy hh:mm' ) -> 08.04.2010 12:01

var DateConverter = {
 dateToString: function( date:java.util.Date, pattern:String ){
  try {
   if( !date ){ return ''; }
  
   var formatter = DateConverter.getFormatter( pattern );
   return formatter.format( date );
  } catch( e ){
   // ErrorHandling
  }
 },
 
 stringToDate: function( dateString:String, pattern:String ){
  try {
   if( !dateString ){ return null; }
  
   var formatter = DateConverter.getFormatter( pattern );
   return formatter.parse( dateString );
  } catch( e ){
   // ErrorHandling
  }
 },
 
 getFormatter: function( pattern:String ){
  try {
   var cacheKey = 'dateFormatter' + pattern;
   var dateFormatter = applicationScope[ cacheKey ];
   if( !dateFormatter ){
    dateFormatter = new java.text.SimpleDateFormat( pattern );
    applicationScope[ cacheKey ] = dateFormatter;
   }
   
   return dateFormatter;
  } catch( e ){
   // ErrorHandling
  }
 } 
}

7 comments:

Dan Herman said...

Thanks for this!! This has saved me a bunch of time since there is no @Format function.

Jocke said...

Was starting to work on my own as I stumbled upon yours.

Saved my some work! Appreciate it! =)

Tom VA said...

Thanks

Spanky said...

wonderful bit of code. THANK YOU for posting it.

-Devin.

mathew said...

Turns out there's a built-in date formatter in the I18n library:

I18n.toString(compositeData.date, 'yyyy-MM-dd');

Anonymous said...

Came in handy. Thank you.

Qaiser said...

Somehow this is not working for me. Can you please share sample code where you guys have used this ?