java.time
It’s not the answer your teacher asked for. Given that it’s a requirement to pass an old-fashioned java.util-Date
object to the constructor, I would do:
LocalDate birthDate = LocalDate.of(1975, Month.JUNE, 4);
Instant startOfDay = birthDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
Person per = new Person("Angelina", "Jolie", Date.from(startOfDay ));
Part of the challenge is that despite the name a Date
does not represent a date. It represents a moment in time (with millisecond precision). In that moment it’s a different date in different time zones of the Earth. The conventional solution to this dilemma is to take the first moment of the day (usually 00:00) in your own time zone. So your Date
representing 4th June 1975 is different from my Date
representing the same date. Oh horrors.
I am using java.time, the modern Java date and time API, as far as I can. In the end I do need to convert to a Date
, of course. My first line of code defines the date of 4th June 1975 more clearly than any of the old date-time classes can. The second line finds the start of the day in the user’s time zone (more precisely, in the default time zone of the JVM where the program is running). Finally Date.from(startOfDay)
converts to a Date
.
Bonus points:
- I find the code clear to read.
- I have made the first step to prepare for the day when either the teacher realizes that there is a better way or we get a better teacher.
Edit: If it is also a requirement that the date be given as 1975-06-04
, just define it in this way instead:
LocalDate birthDate = LocalDate.parse("1975-06-04");
1975-06-04
is ISO 8601 format, the international standard. This is what LocalDate.parse()
expects.
Links