using java Calendar
- by owca
I have a simple task. There are two classes : Ticket and Date. Ticket contains event, event place and event date which is a Date object. I also need to provide a move() method for Date object, so I used Calendar and Calendar's add(). Everything looks fine apart of the output. I constantly get 5,2,1 as the date's day,month,year. Lines with asterix return proper date.
The code :
Ticket class :
public class Ticket {
private String what;
private String where;
private Date when;
public Ticket(String s1, String s2, Data d){
this.what = s1;
this.where = s2;
this.when = d;
}
*public Date giveDate(){
System.out.println("when in giveDate() "+this.when);
return this.when;
}
public String toString(){
return "what: "+this.what+"\n"+"where: "+this.where+"\n"+"when: "+this.when;
}
}
Date class:
import java.util.Calendar;
import java.util.GregorianCalendar;
public class Date {
public int day;
public int month;
public int year;
public Date(int x, int y, int z){
*System.out.println("x: "+x);
*System.out.println("y: "+y);
*System.out.println("z: "+z);
this.day = x;
this.month = y;
this.year = z;
*System.out.println("this.day: "+this.day);
*System.out.println("this.month: "+this.month);
*System.out.println("this.year: "+this.year);
}
public Date move(int p){
*System.out.println("before_change: "+this.day+","+this.month+","+this.year);
Calendar gc = new GregorianCalendar(this.year, this.month, this.day);
System.out.println("before_adding: "+gc.DAY_OF_MONTH+","+gc.MONTH+","+gc.YEAR);
gc.add(Calendar.DAY_OF_YEAR, p);
System.out.println("after_adding: "+gc.DAY_OF_MONTH+","+gc.MONTH+","+gc.YEAR);
this.year = gc.YEAR;
this.day = gc.DAY_OF_MONTH;
this.month = gc.MONTH;
return this;
}
@Override
public String toString(){
return this.day+","+this.month+","+this.year;
}
}
Main for testing :
public class Main {
public static void main(String[] args) {
Date date1=new Date(30,4,2002);
Ticket event1=new Ticket("Peter Gabriel's gig",
"London",date1
);
Ticket event2=new Ticket("Diana Kroll's concert",
"Glasgow",date1
);
Date date2=event2.giveDate();
date2.move(30);
Ticket event3=new Ticket("X's B-day",
"some place",date2
);
System.out.println(date1);
System.out.println(event1);
System.out.println(event2);
System.out.println(event3);
}
}
And here's my output. I just can't get it where 5,2,1 come from :/
x: 30
y: 4
z: 2002
this.day: 30
this.month: 4
this.year: 2002
when in giveDate() 6,12,2004
before_change: 6,12,2004
before_adding: 5,2,1
after_adding: 5,2,1
5,2,1
what: Peter Gabriel's gig
where: London
when: 5,2,1
(...)