Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date in constructor in Java

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.

like image 569
user1091510 Avatar asked Dec 16 '22 06:12

user1091510


1 Answers

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.

like image 145
Jon Skeet Avatar answered Dec 31 '22 11:12

Jon Skeet