How to add days to java.sql.date?

前端 未结 5 2679
猫巷女王i
猫巷女王i 2021-02-20 07:16

Here is my program, I tried

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

相关标签:
5条回答
  • 2021-02-20 07:23

    Here is a method

    private Date sqlDatePlusDays(Date date, int days) {
        return Date.valueOf(date.toLocalDate().plusDays(days));
    }
    
    0 讨论(0)
  • 2021-02-20 07:34

    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())
    
    0 讨论(0)
  • 2021-02-20 07:34
    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());
        }
    
    }
    
    0 讨论(0)
  • 2021-02-20 07:40

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


    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.

    0 讨论(0)
  • 2021-02-20 07:46

    try this :

    Calendar cNow = Calendar.getInstance();  
            Date dNow = cNow.getTime();  
            cNow.add(Calendar.DATE, 7);  
    
            Date dSeven = cNow.getTime();  
    
            SimpleDateFormat format = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a");  
    
            String dateNow = format.format(dNow);  
            String dayBefore = format.format(dSeven);  
            System.out.println(dateNow);  
            System.out.println(daySeven); //here is your current day + 7  
    
            Date date = new Date();  
            System.out.println(date);  
    
    0 讨论(0)
提交回复
热议问题