Thursday 13 March 2014

Best approach for formatting date in java


The most common approach to format the date as required by using SimpleDateFormat.


This approach causes problems when multiple threads access the same instance of the class variable, due to lack of synchronization.


The below are the most frequent exceptions will occurs:
  • java.lang.NumberFormatException
  • java.lang.ArrayIndexOutOfBoundsException

There are two approaches to handle these exceptions in Multi-threading environment.
  1. By using ThreadLocal<SimpleDateFormat>: ThreadLocal is a best appraoch to implement Per Thread Singleton classes or per thread context information.
  2. FastDateFormat.getInstance(): FastDateFormat is available in commons-lang-version.jar. it has several overloaded methods of getInstance() to provide the date format for Thread-safe environment. Please find the API documents here.

Sample code snippet by using SimpleDateFormat:
package com.samples;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleDateFormatExample {
 
 private static DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
 
 public static void main(String[] args) {
  Date currentDate = new Date();
  System.out.println("Current Time: " + dateFormat.format(currentDate));
 }

}



Sample code snippet by using ThreadLocal:
package com.samples;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ThreadLocalDateFormatExample {

 private static ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>() {
  protected DateFormat initialValue() {
   return new SimpleDateFormat("MM/dd/yy");
  }
 };
 
 public static void main(String[] args) {
  Date currentDate = new Date();
  System.out.println("Current Time: " + dateFormat.get().format(currentDate));
 }

}


Sample code snippet by using FastDateFormat:
package com.samples;

import java.util.Date;

import org.apache.commons.lang.time.FastDateFormat;

public class FastDateFormatExample {

 private static final FastDateFormat dateFormat = FastDateFormat.getInstance("dd-MM-yyyy");
 
 public static void main(String[] args) {
  Date currentDate = new Date();
  System.out.println("Current Time: " + dateFormat.format(currentDate));
 }
}

Hence, the best approach is to format the date isby using FastDateFormat if your project has commons-lang.jar dependency, otherwise can use Threadlocal approach.

No comments:

Post a Comment