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.
Date
doesn't have a format. It's just an instant in time, with no associated calendar or time zone. When you need to format a Date
, you would often use a DateFormat
which is told the calendar system to use, the time zone to convert the instant into a local time etc.
When you print out a Date
as you're doing in the second snippet, implicitly via toString()
, that will always use the system default time zone, and an unmodifiable format. (It may or may not change with system locale - I'm not sure). Basically that should only be used for debugging. If you want any sort of control over the text, DateFormat
is where it's at.
If you want to be able to simply construct date values from year/month/day etc, I'd recommend you look at Joda Time - it's a much saner date/time API than Java's. It makes all kinds of things much cleaner, including the separation of "local time", "local date", "local date and time", "date and time in a particular time zone" etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With