Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add days to java.sql.date?

Tags:

java

date

Here is my program, I tried

java.sql.Date logicalDate;
Calendar c = Calendar.getInstance(); 
c.setTime(logicalDate); 
c.add(Calendar.DATE, 1);

The line below is showing an error the constructor Date(date) is undefined

java.sql.Date startDate= new java.sql.Date(c.getTime());

How do I add 1 day to java.sql.Date logicalDate?

like image 359
user2077648 Avatar asked Apr 04 '13 03:04

user2077648


4 Answers

Here is a method

private Date sqlDatePlusDays(Date date, int days) {
    return Date.valueOf(date.toLocalDate().plusDays(days));
}
like image 80
Alexandre Campos Avatar answered Oct 05 '22 23:10

Alexandre Campos


tl;dr

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.

java.time

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 ) ;

Table of date-time types in Java (both legacy and modern) and in standard SQL


About java.time

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?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

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.

like image 42
Basil Bourque Avatar answered Oct 06 '22 01:10

Basil Bourque


Calendar#getTime returns a java.util.Date representation of the Calendar. You really need to use Calendar#getTimeInMillis instead

java.sql.Date startDate= new java.sql.Date(c.getTimeInMillis())
like image 20
MadProgrammer Avatar answered Oct 05 '22 23:10

MadProgrammer


import java.sql.Date;
import java.time.LocalTime;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;

public class Test {

    public static void main(String a[]) {

        java.sql.Date todaysDate = new java.sql.Date(new java.util.Date().getTime());

        int futureDay =1;
        int pastDay=2;

        java.sql.Date futureDate = this.addDays(todaysDate, futureDay);
        java.sql.Date pastDate = this.subtractDays(todaysDate, pastDay);

        System.out.println("futureDate =>>> " + futureDate);
        System.out.println("pastDate =>>> " + pastDate);


    }

    public static Date addDays(Date date, int days) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.DATE, days);
        return new Date(c.getTimeInMillis());
    }

    public static Date subtractDays(Date date, int days) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.DATE, -days);
        return new Date(c.getTimeInMillis());
    }

}
like image 37
Tushar Jamdhade Avatar answered Oct 06 '22 01:10

Tushar Jamdhade