❐ Using java.sql.Date
If your table has a column of type DATE:
-
java.lang.StringThe method
java.sql.Date.valueOf(java.lang.String)received a string representing a date in the formatyyyy-[m]m-[d]d. e.g.:ps.setDate(2, java.sql.Date.valueOf("2013-09-04")); -
java.util.DateSuppose you have a variable
endDateof typejava.util.Date, you make the conversion thus:ps.setDate(2, new java.sql.Date(endDate.getTime()); -
Current
If you want to insert the current date:
ps.setDate(2, new java.sql.Date(System.currentTimeMillis())); // Since Java 8 ps.setDate(2, java.sql.Date.valueOf(java.time.LocalDate.now()));
❐ Using java.sql.Timestamp
If your table has a column of type TIMESTAMP or DATETIME:
-
java.lang.StringThe method
java.sql.Timestamp.valueOf(java.lang.String)received a string representing a date in the formatyyyy-[m]m-[d]d hh:mm:ss[.f...]. e.g.:ps.setTimestamp(2, java.sql.Timestamp.valueOf("2013-09-04 13:30:00"); -
java.util.DateSuppose you have a variable
endDateof typejava.util.Date, you make the conversion thus:ps.setTimestamp(2, new java.sql.Timestamp(endDate.getTime())); -
Current
If you require the current timestamp:
ps.setTimestamp(2, new java.sql.Timestamp(System.currentTimeMillis())); // Since Java 8 ps.setTimestamp(2, java.sql.Timestamp.from(java.time.Instant.now())); ps.setTimestamp(2, java.sql.Timestamp.valueOf(java.time.LocalDateTime.now()));