英文:
Migrate org.joda.time to java.time and set time zone
问题
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?
英文:
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?
答案1
得分: 2
ZonedDateTime pageStart
英文:
No.
withZoneRetainFields
keeps 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 name getRegistrations
it 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 atZoneSameInstant
to get a time in the Europe/Amsterdam
zone, 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 OffsetDateTime
is the one you should almost never use. You probably want ZonedDateTime
. 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 DateTime
object called pageStartDate
?
If you are just interested in dates, then use LocalDate
. If it's actually about a specific moment in time by human reckoning, use ZonedDateTime
. 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 use java.time.Instant
.
`ZonedDateTime pageStart
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论