Customize date using Calendar or DateTime

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

What 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());

      

+3


source to share


2 answers


Version 1 uses a long obsolete class Calendar

. Another problem is that it uses the current JVM timezone setting without being explicit in this code, which could give someone an unpleasant surprise in the future.

Version 2 uses newer classes whenever possible, and it explicitly talks about using the JVM's timezone setting. Good decision.

Version 3 also has the advantages of version 2, but the conversion is in milliseconds from epoch before conversion to Date

. Converting through Instant

in version 2 is more natural and therefore slightly preferable.



As mentioned in the comments, versions 2 and 3 written in the question don't get rid of seconds and fractions of a second. A 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 couldn't use the legacy class at all Date

.

+7


source


if i choose version 1



ZonedDateTime is a new api i not usually used

-2


source







All Articles