Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add more than 30 days with Calendar's add() method in Java

Tags:

java

calendar

I'm not quite sure what field to use when adding more than 30 days to a Java Calendar object. Is there any difference in between Calendar.DAY_OF_MONTH and Calendar.DAY_OF_YEAR?

Example:

GregorianCalendar d = new GregorianCalendar();
d.add(Calendar.DAY_OF_YEAR, 90);

vs

GregorianCalendar d = new GregorianCalendar();
d.add(Calendar.DAY_OF_MONTH, 90);

Thanks.

like image 303
Haes Avatar asked Mar 24 '10 07:03

Haes


People also ask

How do I add 30 days to a specific date in Java?

Adding Days to the given Date using Calendar class Add the given date to the calendar by using setTime() method of calendar class. Use the add() method of the calendar class to add days to the date. The add method() takes two parameter, i.e., calendar field and amount of time that needs to be added.

What is the use of calendar getInstance () in Java?

The getInstance() method in Calendar class is used to get a calendar using the current time zone and locale of the system. Parameters: The method does not take any parameters. Return Value: The method returns the calendar.

How do you add and subtract dates in Java?

DATE field can be used to add or subtract dates in Java. Positive value passed into add() method will add days into date while negative values will subtract days from date in Java. Similarly Calendar. MONTH can be used to add and subtract months from date in Java.


1 Answers

I don't think it makes a difference when you call add. The distinction is important when you call the getters.

Both methods work fine, right? For more than 30 days, as well as negative amounts.

The (admittedly complicated) source for GregorianCalendar#add has this section:

 case DAY_OF_MONTH: // synonym of DATE
 case DAY_OF_YEAR:
 case DAY_OF_WEEK:
    break;
like image 78
Thilo Avatar answered Sep 24 '22 02:09

Thilo