user3243499
user3243499

Reputation: 3161

What is the recommended way to increment date in JAVA?

I am using the Calendar class to increment a date. However, all I see for any month is that it is incrementing until the 31st day of that month, regardless of the month being February or not.

Below is the code I am using now:

long curDayDate = 1524787200;  // April, 27th, 2018

Instant instant = Instant.ofEpochMilli(curDayDate*1000);
LocalDateTime ldt = instant.atZone(ZoneId.of("GMT")).toLocalDateTime();

int gYear   = ldt.getYear();
int gMonth  = ldt.getMonthValue();
int gDay    = ldt.getDayOfMonth();

Calendar Cal = Calendar.getInstance();
Cal.set(gYear, gMonth, gDay);

for(int i = 0; i < 7; i++) {

    // Next day
    Cal.add(Calendar.DATE, 1);
    System.out.println("Next Year = " + Cal.get(Calendar.YEAR) + ", Next Month = " + Cal.get(Calendar.MONTH) + ", Next Date = " + Cal.get(Calendar.DATE));
}

The above code goes until the 31st of April, even though there is no 31st day for the month of April.

Upvotes: 0

Views: 97

Answers (1)

Andy Turner
Andy Turner

Reputation: 140554

Don't use Calendar. It is part of a raft of poorly-designed date/time APIs that were introduced in early versions of Java (Calendar was introduced in JDK 1.1), and supplanted by the java.time package introduced in Java 8.

If you want to add a day to a LocalDateTime, use plusDays.

Upvotes: 5

Related Questions