Date in constructor in Java
•
Java
I have a constructor class:
... 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 is not part of your homework I really don't know what to do
Solution
You can create 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 rightly pointed out, this has been abandoned, which means that other methods are more popular You can also create 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 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); }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码