I need to add the current date into a prepared statement of a JDBC call. I need to add the date in a format like yyyy/MM/dd
.
I\'ve try with
Will do:
new Date(Instant.now().toEpochMilli())
A java.util.Date
is not a java.sql.Date
. It's the other way around. A java.sql.Date
is a java.util.Date
.
You'll need to convert it to a java.sql.Date
by using the constructor that takes a long that a java.util.Date
can supply.
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
Simply in one line:
java.sql.Date date = new java.sql.Date(Calendar.getInstance().getTime().getTime());
new java.sql.Date(Calendar.getInstance().getTimeInMillis());
myPreparedStatement.setObject( // Directly exchange java.time objects with database without the troublesome old java.sql.* classes.
… ,
LocalDate.parse( // Parse string as a `LocalDate` date-only value.
"2018-01-23" // Input string that complies with standard ISO 8601 formatting.
)
)
The modern approach uses the java.time classes that supplant the troublesome old legacy classes such as java.util.Date
and java.sql.Date
.
For a date-only value, use LocalDate
. The LocalDate class represents a date-only value without time-of-day and without time zone.
The java.time classes use standard formats when parsing/generating strings. So no need to specify a formatting pattern.
LocalDate ld = LocalDate.parse( input ) ;
You can directly exchange java.time objects with your database using a JDBC driver compliant with JDBC 4.2 or later. You can forget about transforming in and out of java.sql.* classes.
myPreparedStatement.setObject( … , ld ) ;
Retrieval:
LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
In order to get "the current date" (as in today's date), you can use LocalDate.now()
and pass that into the java.sql.Date
method valueOf(LocalDate)
.
import java.sql.Date;
...
Date date = Date.valueOf(LocalDate.now());