How do I add two integer values ​​as year and month to a date variable?

I am using NetBeans IDE 8.0 Beta.

I have 2 integers with values ​​retrieved from a database table.

int year, month;
try{
      string sql = "select * from item where item_id = i001";
      pst = conn.prepareStatement(sql);
      rs = pst.executeQuery();

      rs.next();
      year = Integer.parseInt(rs.getString("warr_years"));
      month = Integer.parseInt(rs.getString("warr_months"));

}
catch(SQLException e){
}

      

And I have a String variable that contains the current date.

        DateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd");
        Date date = new Date();
        String d = dateFormat.format(date);

      

Now I need to add years and months to the date. Can anyone help me with this?

+3


source to share


2 answers


For this you will need Calender

.



Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.YEAR, year);
c.add(Calendar.MONTH, month);
Date newDate = c.getTime();

      

+3


source


First your format is year

off. It's "yyyy" not "YYYY". Then you can use Calendar

and something like

int year = 10;
int month = 2;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, year);  // <-- add year years to the Calendar.
cal.add(Calendar.MONTH, month);// <-- add month months to the Calendar.
System.out.println(dateFormat.format(cal.getTime())); // <-- display the result

      



The above code outputs (today, Aug 27, 2014) -

2024-10-27

      

+1


source







All Articles