如何将日期增加到特定日期以插入数据?

时间:2017-11-15 06:58:34

标签: java sql jdbctemplate

我有一个准备好的声明,如下所示,将其插入postgres数据库:

 String InsertQuery="INSERT INTO public.user_daily_activity (id,user,day,time) 
 values (?,?,?,?)";
 String date="2017-11-16";
try{
   jtmTemplate.update(InsertQuery, new PreparedStatementSetter() {
   public void setValues(PreparedStatement preparedStatement) throws SQLException {
   preparedStatement.setInt(1, id);
   preparedStatement.setString(2, user);
   preparedStatement.setDate(3, java.sql.Date.valueOf(date));
   preparedStatement.setInt(4, time);

}

所以现在取决于我需要将其从开始日期增加到11月30日的日期。例如,如果date = "2017-11-16",那么我需要从"2017-11-16" to "2017-11-30"插入。如果date = "2017-11-27",那么我需要从"2017-11-27"插入"2017-11-30"

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

嗯,这里有一个使用pre-java8 DateCalendar的解决方案:

public void incrementDate() {
    int dayLimit = 30;
    // month is zero-based index
    int monthLimit = 10;
    String startStringDate = "2017-11-16";
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Calendar calendar = Calendar.getInstance();
    Date startDate;
    java.sql.Date sqlDate;
    try {
        startDate = dateFormat.parse(startStringDate);
        calendar.setTime(startDate);
        while(calendar.get(Calendar.DAY_OF_MONTH) <= dayLimit && calendar.get(Calendar.MONTH) <= monthLimit) {
            sqlDate = new java.sql.Date(startDate.getTime());
            // here just use sqlDate in your prepared statement
            //...
            //e.g. preparedStatement.setDate(3, sqlDate);
            // ...
            System.out.println("Using sql date : " + sqlDate);
            calendar.setTime(startDate);
            calendar.add(Calendar.DATE, 1);
            startDate = calendar.getTime();
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
}