0

I need to convert a date (without time component), chosen using toedter JCalendar, to an SQL Timestamp (i.e. with 0:00:00 time part) to use it in SQL queries.

I there nothing more simple or elegant than this? What is recommended?

Date dt = jCalendar1.getDate();
Timestamp ts = Timestamp.valueOf(dt.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().atStartOfDay());
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Tom
  • 423
  • 1
  • 4
  • 13

1 Answers1

1

You can simply use a java.sql.Date and PreparedStatement.setDate, then Jaybird will handle the conversion from the date to a timestamp with time set to 00:00:00.0 for you. An example:

java.util.Date dt = jCalendar1.getDate();
java.sql.Date sqlDate = new java.sql.Date(dt.getTime());
pstmt.setDate(1, sqlDate);
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Thanks a lot, but it does not seem to work for me. Throws no exception, but the resultset is not correct (is empty). My SQL code is "WHERE KalDatum = ?". KalDatum is Timestamp. The trouble might be that my DB is unfortunatelly Dialect 1 (this is why I must work only with Timestamps). – Tom Dec 01 '16 at 10:23
  • @Tom In dialect 1 a `DATE` is a timestamp, are you sure that those dates have time zero? – Mark Rotteveel Dec 02 '16 at 11:06
  • Sorry, I am a total amateur. jCalendar1.getDate() aparently does not have time zero. I understood your suggestion that your code will automatically set time to 0 in the resulting timestamp - the same as my code does using atStartofDay(). My test of your code: if I set dt manually to Date with non-zero time, my resultset is wrong (empty); if set to zero time Date, it works. – Tom Dec 02 '16 at 15:03
  • @Tom Hmm, that is not exactly what I expected, but I might have confused the behavior of Jaybird 2.2 with the behavior of the upcoming Jaybird 3.0. – Mark Rotteveel Dec 02 '16 at 15:31