Here is my program, I tried
java.sql.Date logicalDate;
Calendar c = Calendar.getInstance();
c.setTime(logicalDate);
c.add(Calendar.DATE, 1);
Never use the terrible legacy classes java.sql.Date
, java.util.Calendar
, java.util.GregorianCalendar
, and java.util.Date
. Use only java.time classes.
How do I add 1 day to java.sql.Date logicalDate?
Convert from legacy class java.sql.Date
to modern class java.time.LocalDate
. Then call plus…
/minus…
methods to add/subtract days, weeks, months, or years.
myJavaSqlDate.toLocalDate().plusDays( 1 )
If given a Calendar
that is actually a GregorianCalendar
, and you want only the date, convert to ZonedDateTime
and extract a LocalDate.
( (GregorianCalendar) myCal ) // Cast from general `Calendar` to more concrete class `GregorianCalendar`.
.toZonedDateTime() // Convert from the legacy class to the modern `ZonedDateTime` class replacement.
.toLocalDate() // Extract the date only, omitting the time-of-day and the time zone.
.plusWeeks( 1 ) // Returns a `LocalDate` object, a date without a time-of-day and without a time zone.
The badly designed java.sql.Date
class was years ago supplanted by the modern java.time classes with the unanimous adoption of JSR 310. Avoid Calendar
class too.
Retrieve from your database with JDBC 4.2 by calling ResultSet::getObject.
LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;
Add a week by calling LocalDate::plusWeeks.
LocalDate weekLater = ld.plusWeeks( 1 ) ;
Write to database by calling PreparedStatement::setObject.
myPreparedStatement.setObject( … , weekLater ) ;
Best to avoid the troublesome legacy date-time classes entirely. But if you need a java.sql.Date object to interoperate with old code not yet updated to java.time, use new conversion methods added to the old classes. Specifically, java.sql.Date.valueOf.
java.sql.Date d = java.sql.Date.valueOf( ld ) ;
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
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.