nimo23
nimo23

Reputation: 5698

set up Date with Calendar or DateTime

I want to set the hour and the minute of a date-instance. I have 3 solutions.

Which should I take and why? :

version 1:

Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 8);
calendar.set(Calendar.HOUR, 30);

return calendar.getTime();

version 2:

ZonedDateTime i = date.toInstant()
.atZone(ZoneId.systemDefault())
.withHour(8)
.withMinute(30);

return Date.from(i.toInstant());

version 3:

ZonedDateTime i = date.toInstant()
.atZone(ZoneId.systemDefault())
.withHour(8)
.withMinute(30);

return new Date(i.toEpochSecond());

Upvotes: 3

Views: 125

Answers (2)

Anonymous
Anonymous

Reputation: 86379

Version 1 is using the long outdated Calendar class. Another problem with it is that it is using the JVM’s current time zone setting without being explicit about this in the code, a trait that could give someone an unpleasant surprise some time in the future.

Version 2 is exploiting the newer classes as far as possible, and it is explicit about using the JVM’s time zone setting. The good solution.

Version 3 has the benefits of version 2 too, but a conversion to milliseconds since the epoch before converting to Date. The conversion via Instant in version 2 is more natural and therefore slightly preferred.

As has been mentioned in the comments, versions 2 and 3 as written in the question do not get rid of seconds and fraction of second. The simple solution (given that you want this) is to use truncatedTo():

    ZonedDateTime i = date.toInstant()
            .atZone(ZoneId.systemDefault())
            .withHour(8)
            .withMinute(30)
            .truncatedTo(ChronoUnit.MINUTES);

Best of all of course if you could avoid using the also outdated Date class altogether.

Upvotes: 7

user8118435
user8118435

Reputation: 1

if i pick version 1

ZonedDateTime is new api i not commonly used

Upvotes: -2

Related Questions