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

Pravin yadav
  • 567
  • 1
  • 6
  • 16
  • have you tried with SimpleDateFormate ? – Vishal Gajera Dec 25 '15 at 10:57
  • http://stackoverflow.com/questions/3307330/using-joda-date-time-api-to-parse-multiple-formats – Anatoly Dec 25 '15 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. – Tiny Dec 25 '15 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. – Basil Bourque Dec 27 '15 at 09:26

1 Answers1

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());
Javitronxo
  • 817
  • 6
  • 9
  • 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 – Pravin yadav Dec 25 '15 at 17:09
  • 1
    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)` – Javitronxo Dec 25 '15 at 17:26