クリーンな方法は、可能な日付フォーマット用のカスタムのDataBinderを登録することが考えられます。
beans = {
"customEditorRegistrar"(CustomEditorRegistrar)
}
:また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のアプリ/ confに/春/ resources.groovyに春のBean定義を作成する必要があると思い
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
}
}
}
}
そして最終的にあなたのgrails-app/conf/Config.groovyに日付フォーマットを定義する:
grails.date.formats = ["yyyy-MM-dd HH:mm:ss.SSS ZZZZ", "dd.MM.yyyy HH:mm:ss"]
GroovyではなくJavaで(上記のように)これを実装する理由があるのだろうかと思いますか? Groovyではコードがかなり短くなります。 –
Groovyが以前よりずっと遅かった時代にJavaで同様のコードを実装しました。 Groovyはこの問題で大きな飛躍を遂げました。私は怠惰から古くなったJavaコードを再利用しています;-) –
あなたがやるべきことの古典的なコードです。もっともきれいな方法は、解析の試行を繰り返すのではなく、ロケールを使用してフォーマットを取得することです。 – Gepsens