12

这是我的程序,我试过了

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

下面的行显示构造函数 Date(date) 未定义的错误

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

如何将 1 天添加到 java.sql.Date logicalDate?

4

5 回答 5

12

Calendar#getTime返回 的java.util.Date表示形式Calendar。你真的需要Calendar#getTimeInMillis使用

java.sql.Date startDate= new java.sql.Date(c.getTimeInMillis())
于 2013-04-04T03:30:31.547 回答
3
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());
    }

}
于 2018-04-20T07:16:24.993 回答
3
于 2020-01-11T18:51:29.333 回答
2

这是一个方法

private Date sqlDatePlusDays(Date date, int days) {
    return Date.valueOf(date.toLocalDate().plusDays(days));
}
于 2020-01-11T14:54:20.353 回答
1

试试这个 :

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);  
于 2013-04-05T07:08:51.300 回答