I want to migrate this code:
private Resource getRegistrations(DateTime startDate) {
DateTime pageStartDate = (startDate == null) ? null : startDate.withZoneRetainFields(DateTimeZone.UTC);
return ........;
}
to this:
private Resource getRegistrations(OffsetDateTime startDate) {
OffsetDateTime pageStartDate = (startDate == null) ? null : startDate.atZoneSameInstant(ZoneId.of("UTC")).toOffsetDateTime();
return null;
}
Is this the proper way atZoneSameInstant(ZoneId.of("UTC")).toOffsetDateTime(); To set the time zone?
No.
withZoneRetainFieldskeeps the 'fields' - year, month, day, hour, minute - those are fields. By changing the timezone, the first snippet means that the timestamp returned is not the same as the input value. Given the namegetRegistrationsit strongly sounds to me like the first code is wrong. This happens: You are refactoring, and you found a bug.The second snippet maintains the same instant. In other words, if you have, say, '5 o'clock in the afternoon, december 20th, in london' and you use
atZoneSameInstantto get a time in theEurope/Amsterdamzone, you'd get 6 o clock back (because when it's 5 o'clock in london, it's 6 in amsterdam, amsterdam is in a time zone 1 hour ahead of britain).The first snippet would give you 5 o'clock in amsterdam which is in fact 1 hour earlier.
Note that
OffsetDateTimeis the one you should almost never use. You probably wantZonedDateTime. The problem with offsets is that they do not map onto any reckoning at all. Computers don't like offsets (they like millis-since-an-epoch), and humans don't use offsets, they use timezones. There's no difference if it's a zone that doesn't have daylight savings, but many do.Your variable is also wrong. Why is a
DateTimeobject calledpageStartDate?If you are just interested in dates, then use
LocalDate. If it's actually about a specific moment in time by human reckoning, useZonedDateTime. If it's about computer systems / raw comparisons (you just want to know which event amongst a whole bunch of em was 'earlier' than another, you don't really care about which date it was on, for example), then usejava.time.Instant.`ZonedDateTime pageStart