我在Vaadin中使用了一个带有转换器的DateField来启用java.time包的LocalDateTime。
当我使用Converter并通过setRangeEnd()限制DateField时,DateField总是显示一条带有“Date is out of allowed Range”消息的UserError。没有使用转换器它工作正常。
我的转换器:
public class LocalDateTimeToDateConverter implements Converter<Date,LocalDateTime> {
private static final long serialVersionUID = -4900262260743116965L;
@Override
public LocalDateTime convertToModel(Date value, Class<? extends LocalDateTime> targetType, Locale locale)
throws com.vaadin.data.util.converter.Converter.ConversionException {
if (value != null) {
return value.toInstant().atZone(ZoneOffset.systemDefault()).toLocalDate().atStartOfDay();
}
return null;
}
@Override
public Date convertToPresentation(LocalDateTime value, Class<? extends Date> targetType, Locale locale)
throws com.vaadin.data.util.converter.Converter.ConversionException {
if (value != null) {
return Date.from(value.atZone(ZoneOffset.systemDefault()).toInstant());
}
return null;
}
@Override
public Class<LocalDateTime> getModelType() {
return LocalDateTime.class;
}
@Override
public Class<Date> getPresentationType() {
return Date.class;
}
}
MyView在哪里使用DateField:
dateField = new DateField();
dateField.setDateFormat("yyyy-MM-dd");
dateField.setRangeStart(null);
dateField.setRangeEnd(Date.from(lastAvailableDataDate.atZone(ZoneId.systemDefault()).toInstant()));
dateField.setConverter(new LocalDateTimeToDateConverter());
任何人都知道如何在使用转换器时设置范围?
答案 0 :(得分:0)
我目前解决此问题的方法是扩展DateField类。
public class MyDateField extends DateField {
private static final long serialVersionUID = -7056642919646970829L;
public MyDateField() {
super();
}
public LocalDateTime getDate() {
Date value = super.getValue();
return DateToLocalDateTime(value);
}
public void setDate(LocalDateTime date) {
super.setValue(LocalDateTimeToDate(date));
}
public void setRange(LocalDateTime start, LocalDateTime end) {
if (start != null) {
super.setRangeStart(LocalDateTimeToDate(start));
} else {
super.setRangeStart(null);
}
if (end != null) {
super.setRangeEnd(LocalDateTimeToDate(end));
} else {
super.setRangeEnd(null);
}
}
private Date LocalDateTimeToDate(LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
private LocalDateTime DateToLocalDateTime(Date date) {
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
}
现在不再需要转换器了,get / setDate()方法与我们的swing datepicker方法相对应。 对于我们的情况,这可能是最好的解决方案。