-3

I'm trying to figure out how to increment dates in JAVA.

The date I'm trying to increment is, 2012-10-01.

The following represents the increments:

  • 2012-10-01 - 2013-09-30
  • 2013-10-01 - 2014-09-30
  • 2014-10-01 - 2015-09-30
  • 2015-10-01 - 2016-09-30

4 Answers4

2

With the new Java time API you can use a LocalDate:

LocalDate date = LocalDate.parse("2012-10-01");

for (int i = 0; i < 4; i++) {
  System.out.println(date + " - " + date.plusYears(1).minusDays(1));
  date = date.plusYears(1);
}
assylias
  • 321,522
  • 82
  • 660
  • 783
1

Please try this,

  Calendar c = Calendar.getInstance();
  c.setTime(randomDate);
  c.add(Calendar.YEAR, n);
  newDate = c.getTime();

It is here

Community
  • 1
  • 1
bobs_007
  • 178
  • 1
  • 10
  • It works and it adds a year. Though, what I'm trying to achieve is to have a date range. From 2012-10-01 - 2013-09-30, 2013-10-01 - 2014-09-30. So the safest question can be, how can I increment a specific date to a day behind the next year. – Vincent Mercado Sy Jun 04 '15 at 07:50
  • @VincentMercadoSy You can do c.add(Calendar.DATE, -1) to minus a day from the date – bobs_007 Jun 04 '15 at 08:06
0

Use following code

import java.util.Calendar;
import java.text.SimpleDateFormat;

public class HelloWorld {
  public static void main(String[] args) {

    Calendar cal = Calendar.getInstance();
    SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
    cal.set(Calendar.YEAR, 2010);
    cal.set(Calendar.MONTH,9); //Month start with 0=> Jan 
    cal.set(Calendar.DATE,01);
    System.out.println(dateformat.format(cal.getTime()));
        cal.add(Calendar.YEAR,1);
        cal.add(Calendar.DATE,-1);
        System.out.println(dateformat.format(cal.getTime()));


 } 
}
Sarit Adhikari
  • 1,344
  • 2
  • 16
  • 28
0

how about use joda-time.jar e.g

public static String getTargetDate(String date)
{
    DateTime dt = new DateTime(date);
    DateTime dt2 = dt.plusYears(1);
    dt2 = dt2.minusDays(1);
    return dt2.toString().substring(0, 10);
}