I need to deal with New York, London and Tokyo time zone in the same application. Some time it is quite difficult to manage.
This is how I convert ZonedDateTime
to LocalDate
. In functionOne
, you can't guarantee the timezone of parameter dateTime
is the one you expect. Before you convert to LocalDate
, you always need to change the timezone first.
void functionOne(ZonedDateTime dateTime) {
var date = dateTime.withZoneSameInstance(londonZoneId).toLocalDate();
// use the date
}
If they provide a function ZonedDateTime.toLocalDate(ZoneId zoneId)
, it would be less error prone I think. It can force people to provide a ZoneId
when they get the LocalDate
.
This is another solution I can think of. We create a date time type for each timezone.
class LondonDateTime {
private final ZonedDateTime dateTime;
public LondonDateTime(ZonedDateTime dateTime) {
this.dateTime = dateTime.withZoneSameInstance(londonZoneId);
}
public ZonedDateTime getDateTime() { return dateTime; }
public LocalDate getLocalDate() { return dateTime.getLocalDate(); }
}
void functionTwo(LondonDateTime dateTime) {
var date1 = dateTime.getDateTime().toLocalDate();
// or
var date2 = dateTime.toLocalDate();
}
Top comments (0)