It's trivial to create a Duration as a given amount of given units:
Duration duration = Duration.of(3, ChronoUnit.HOURS);
But there is no such method for Period. What is the best way to do this?
I have a situation where i have a unit and a count as variables, so can't simply hardcode a call to Period::ofYear or similar.
This is the cleanest thing i came up with:
Period period = Period.from(new TemporalAmount() {
@Override
public long get(TemporalUnit unitToGet) { return unitToGet.equals(unit) ? amount : 0; }
@Override
public List<TemporalUnit> getUnits() { return List.of(unit); }
@Override
public Temporal addTo(Temporal temporal) { throw new UnsupportedOperationException(); }
@Override
public Temporal subtractFrom(Temporal temporal) { throw new UnsupportedOperationException(); }
});
This is clean in the sense that it avoids having to embed the knowledge of what units a Period can have, although this is probably excessively purist. It seems verbose for such a simple operation, though!