22/08/2013

[Java] String to Date and vice versa

When working with dates in Java you'll often find yourself having to convert them from a String object to a Date object and vice versa. These function snippets will allow you to easily perform the conversion operations, no third-party libraries needed:

Imports

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;


string2Date

 /** Converts given String in a Date object with specific format  
  * @param date - a String representing the date to convert. IT MUST BE in the given format  
  * @param dateFormat - a String specifying the format of the date e.g: dd/MM/yyyy  
  * @return a Date object, {@null} if the given string is {@null} or if there's been a conversion error  
  * */  
 public static Date string2Date(String date, String dateFormat){  
      Date d = null;  
      try{  
           if(date!=null && !date.equalsIgnoreCase("") && dateFormat!=null && !dateFormat.equalsIgnoreCase("")) d = new SimpleDateFormat(dateFormat, Locale.ITALIAN).parse(date);//or whatever Locale you need  
      }catch(Exception e){}//you could always decide to raise the exception rather than returning simply NULL  
      return d;  
 }  

date2String

 /** Converts given Date in a String object with specific format  
 * @param date - a Date to be represented as a string. IT MUST BE in the given format  
 * @param dateFormat - a String specifying the format of the date e.g: dd/MM/yyyy  
 * @return a String object, {@null} if the given date is {@null} or if there's been a conversion error  
 * */  
 public static String date2String(Date date, String dateFormat){  
      Format formatter = new SimpleDateFormat(dateFormat);  
      String s = null;  
      try{  
           if(date!=null && dateFormat!=null && !dateFormat.equalsIgnoreCase(""))s = formatter.format(date);  
      }catch(Exception e){}//you could always decide to raise the exception rather than returning simply NULL  
      return s;  
 }  

Of course, if you prefer, rather than returning NULL if something went wrong, you could always raise an Exception. You can find all accepted formats in the SimpleDateFormat JavaDoc.

No comments:

Post a Comment

With great power comes great responsibility