I have a class with the constructor:
...
Date d1;
Date d2;
public DateClass(Date d1, Date d2) {
this.d1 = d1;
this.d2 = d2;
}
...
Then in another class I want to use this constructor:
...
DateClass d = new DateClass(what I should I write here to create Date in format mm-dd-yyyy);
System.out.println(d);
...
Thank you! P.S This in not a part of a homework. I really do not know how to do it.
You can make a new Date
by calling the constructor.
// you specify year1, month1, day1
DateClass d = new DateClass(new Date(year1-1900, month1-1, day1),
new Date (year2-1900, month2-1, day2);
This is the simplest way, and will certainly work; however, as Carlos Heuberger correctly notes, this is deprecated, meaning that other ways are preferred. You can also make a new Date
through DateFormat
:
DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
Date d1 = df.parse("12-10-2011"); // for example, today's date
Date d2 = df.parse("01-01-1900"); // use your own dates, of course
To be able to print in mm-dd-yyyy
format, implement toString
:
public String toString(){
DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
return "Date 1: " + df.format(d1) + " Date 2: " + df.format(d2);
}