-1

I'm currently making a program that needs me to make a method that will add + 1 to the day of an existing objects date attribute. The problem is I'm not entirely sure how I modify it's value, I've tried day = day + 1, this.day + 1, etc.

So let's assume that an object date1 was equal to 1/1/1970 and I ran date1.tomorrow(); it would modify it and make it 2/1/1970.

EDIT: I'm not using java.util.Date, I made a constructor called Date with 3 fields in it.

3 Answers3

3

You can't directly modify a Date object by adding the integer 1 to it. This is because they are of different types. I suggest using the Calendar object; it has a method called Calendar#add(int field, int amount. That will do what you're trying to do.

EDIT: I had more detailed instructions, but since this question sounds like homework, I'm just leaving you with the hint above. At any rate, it should be enough to point you in the right direction.

Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
1

try this:

Calendar c = Calendar.getInstance(); 
c.setTime(yourDate); 
c.add(Calendar.DATE, 1);
yourDate = c.getTime();

EDIT

So let's assume that an object date1 was equal to 1/1/1970 and I ran date1.tomorrow(); it would modify it and make it 2/1/1970.

If your date object (say dt), is an java.util.Date, you cannot do dt.tomorrow() unless you extend util.Date you could create a util class/method. e.g.:

class Foo {
....

public static Date tomorrow(java.util.Date yourDate){
Calendar c = Calendar.getInstance(); 
    c.setTime(yourDate); 
    c.add(Calendar.DATE, 1);
    return c.getTime();
}

then call it:

dt = Foo.tomorrow(dt);
Kent
  • 189,393
  • 32
  • 233
  • 301
0

If you're dealing with objects of java.util.Date using the + operator on those objects isn't valid.

More importantly, even if the + operator had been legal, it wouldn't make any sense using it - date + 1 should add 1 to the date or month or year..?

To manipulate an object of java.util.Date the class Calendar provides several utility methods. One of those which you can use here is Calendar.add.

Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. For example, to subtract 5 days from the current time of the calendar, you can achieve it by calling:

add(Calendar.DAY_OF_MONTH, -5)

Edit:

It appears from your edit that you aren't using java.util.Date objects. Now that your Date object maintains three properties (most likely date, month and year), you should be able to apply arithmetic operators on those fields.

However you should be careful to follow date related rules while manipulating those fields (assuming they belong to one of the integral types).

For example adding 1 day to 28/02/2013 should update both date and month of the Date instance.