I have the following code to convert different string representations of date/datetime into timestamp object:
public class GeneralMethods {
public static String[] formats = {"dd/mm/yyyy","mm/dd/yyyy hh:mm:ss","E MMM dd HH:mm:ss zzz yyyy"};
/**
* a method to return timestamp object from string date in the formats
* {"dd/mm/yyyy HH:mm:ss","E MMM dd HH:mm:ss zzz yyyy","dd/mm/yyyy"}
* @param date: the date to format in string representation
* @return timestamp object
*/
public static Timestamp timestampFormat(String date)
{
Date dateObj = new Date();
for(String format: formats)
{
try
{
dateObj = new SimpleDateFormat(format).parse(date);
System.out.println(dateObj.toString()); // for tracking
}catch (ParseException e)
{
}
}
return new Timestamp(dateObj.getTime());
}
// testing
public static void main (String args[])
{
System.out.println(timestampFormat("05/31/2011 21:37:35"));
}
}
the output from this code is:
Wed Jan 05 00:31:00 GMT 2011
Mon Jan 31 21:37:35 GMT 2011
2011-01-31 21:37:35.0
as you can see the month in the output is wrong for the input 05/31/2011 21:37:35. how this is happening?