最彻底的方法可能是注册可能的日期格式自定义DataBinder的。
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CustomDateBinder extends PropertyEditorSupport {
private final List<String> formats;
public CustomDateBinder(List formats) {
List<String> formatList = new ArrayList<String>(formats.size());
for (Object format : formats) {
formatList.add(format.toString()); // Force String values (eg. for GStrings)
}
this.formats = Collections.unmodifiableList(formatList);
}
@Override
public void setAsText(String s) throws IllegalArgumentException {
if (s != null)
for (String format : formats) {
// Need to create the SimpleDateFormat every time, since it's not thead-safe
SimpleDateFormat df = new SimpleDateFormat(format);
try {
setValue(df.parse(s));
return;
} catch (ParseException e) {
// Ignore
}
}
}
}
你想也需要实现PropertyEditorRegistrar的
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import grails.util.GrailsConfig;
import java.util.Date;
import java.util.List;
public class CustomEditorRegistrar implements PropertyEditorRegistrar {
public void registerCustomEditors(PropertyEditorRegistry reg) {
reg.registerCustomEditor(Date.class, new CustomDateBinder(GrailsConfig.get("grails.date.formats", List.class)));
}
}
,并在您的grails-app/conf目录/春/ resources.groovy创建一个Spring bean定义:
beans = {
"customEditorRegistrar"(CustomEditorRegistrar)
}
,最后在你的grails-app/conf/Config.groovy中定义日期格式:
grails.date.formats = ["yyyy-MM-dd HH:mm:ss.SSS ZZZZ", "dd.MM.yyyy HH:mm:ss"]
想知道是否有一个原因,你会选择在Java(如上),而不是Groovy中实现这个? Groovy的代码会比较短。 – 2009-10-22 00:42:25
我以前在Groovy比现在慢得多时,在Java中实现了一段类似的代码。 Groovy在这件事上做了一个巨大的飞跃。我只是懒惰的重用旧的Java代码;-) – 2009-10-22 09:42:04