Showing posts with label server side javascript. Show all posts
Showing posts with label server side javascript. Show all posts

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
  }
 } 
}