0

I want to convert a string representation of date in any format to java.sql.Timestamp,(format is also provided)

we have tried using Timestamp.valueOf() and Date.valueOf() but both these method requires String in a particular format,What i need is a generic method which will convert a given String date in any format to java.sql.Timestamp

Thanks in Advance

4
  • have you tried with SimpleDateFormate ? Commented Dec 25, 2015 at 10:57
  • stackoverflow.com/questions/3307330/… Commented Dec 25, 2015 at 11:38
  • java.sql.Timestamp itself has no format at all and is supposed to be used on the back-end side (JDBC). java.sql.Timestamp represents the number of milliseconds, since January 1, 1970, 00:00:00 GMT. Formatting a date (using SimpleDateFormat, for example) in a specific format is only involved, when a date is to be displayed somewhere which java.sql.Timestamp is not meant for. Commented Dec 25, 2015 at 17:25
  • @ctdex Please search StackOverflow before posting. The question of parsing any arbitrary date-time format has been addressed many many times already. Commented Dec 27, 2015 at 9:26

1 Answer 1

1

If you have the string and know the format you can try something like:

dateStr = "25 December 2015"
date = new SimpleDateFormat("dd MMMM yyyy", Locale.ENGLISH).parse(dateStr);
java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(date.getTimestamp());

Or similar:

SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
java.util.Date date = simpleDate.parse("2015-12-31 09:45:52.189");
java.sql.Timestamp = new java.sql.Timestamp(date.getTime());
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks,yes that's works but what if we don't know the format beforehand it is possible with SimpleDateFormat,by the way i am using java7
I don't know a specific method for that. You could try to define several date formats, and surround the method with a try {} catch (ParseException e)

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.