가장 깨끗한 방법은 가능한 날짜 형식에 대한 사용자 정의 DataBinder를 등록 아마.
beans = {
"customEditorRegistrar"(CustomEditorRegistrar)
}
:
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에서 스프링 빈 정의를 작성해야하는 것
그리고 마지막으로 grails-app/conf/Config.groovy에 날짜 형식을 정의하십시오 :
grails.date.formats = ["yyyy-MM-dd HH:mm:ss.SSS ZZZZ", "dd.MM.yyyy HH:mm:ss"]
그루비가 아닌 자바로 구현할 이유가 있다면 궁금하십니까? 코드는 Groovy로 꽤 짧을 것입니다. –
그루비가 지금보다 훨씬 느린 자바에서 비슷한 코드를 구현했습니다. Groovy는이 문제에서 큰 도약을했습니다. 나는 단지 오래된 자바 코드를 게으르지 않게 재사용하고있다 ;-) –
멋진 코드 조각, 당신이하는 일의 고전. 가장 깨끗한 방법은 구문 분석을 통해 반복하지 않고 Locale을 사용하여 형식을 검색하는 것입니다. – Gepsens