Java 参数化ZoneDateTime方法
我有一个参数化方法:Java 参数化ZoneDateTime方法,java,design-patterns,modularity,Java,Design Patterns,Modularity,我有一个参数化方法: private static Date getTimeFor(int hour, int minute, int second, int nanoSecond, String zoneId) { ZonedDateTime time = ZonedDateTime.now() .withZoneSameLocal(ZoneId.of(zoneId)) .withHour(hour) .withM
private static Date getTimeFor(int hour, int minute, int second, int nanoSecond, String zoneId) {
ZonedDateTime time = ZonedDateTime.now()
.withZoneSameLocal(ZoneId.of(zoneId))
.withHour(hour)
.withMinute(minute)
.withSecond(second)
.withNano(nanoSecond);
return Date.from(time.toInstant());
}
其次是:
private Date getRomeStartTime(){
return getTimeFor(8,30,0,0,"Europe/Rome");
}
private Date getParisStartTime(){
return getTimeFor(9,30,0,0,"Europe/Paris");
}
private Date getLondonStartTime(){
return getTimeFor(9,00,0,0,"Europe/London");
}
随着更多城市的增加,这可能会很快失控。我的目标只是公开/公开以下方法,并将StartTimes的构建委托给其他地方:
public Date getEffectiveTimeFor(String zoneId){
// Delegate construction as per zoneId elsewhere
// dont want to use a long-winded if-else statement
}
我不能使用策略模式,因为我不应该传递对象,而应该只传递字符串。
这里最好的方法是什么
(p.s.I必须返回旧的
日期
,这是不可能的)您只需使用地图
存储每个区域ID的开始时间。然后在您的方法中从该地图获取开始时间,并从那里创建日期。好,您可以使用地图存储每个区域ID的开始时间。这就是您要问的吗?是的,正是它!非常感谢。我的想法一直围绕着模式和功能接口,因为我最近花了太多时间在它们上面。这使我忽略了这样一个简单的解决办法。请随意回答,我将在ZonedDateTime
中接受,您也可以使用(LocalTime.of(hour,min,sec,nanosec))调用。如果您使用@JBNizet建议的map解决方案,那么with(LocalTime)
调用会更好,因为它使代码更清晰、更短(IMO)