1

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?

1 Answer 1

2

mm is for minutes MM is for months so with your patterns you set minutes and months are set by default to January.

Try changing your patterns to "dd/MM/yyyy", "MM/dd/yyyy hh:mm:ss"

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.