Grails时间类型自动转换的格式设置(in/out)
程序员文章站
2022-05-19 21:41:47
...
1.Domain转换为json简单,直接在BootStrap的init里面添加:
JSON.registerObjectMarshaller(Date) { return it?.format("yyyy-MM-dd HH:mm:ss") }
ps:还有一种方法是利用插件,重写Date的toString方法.
参见:http://*.com/questions/690370/how-to-return-specific-date-format-as-json-in-grails
2.js段提交数据到controller,自动转换为DATE.
1)在src/groovy添加:
package utils import java.beans.PropertyEditorSupport; import java.text.ParseException; import java.text.SimpleDateFormat; /** * 自定义的Date转换器,支持多种format */ 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 } } } }
2)添加CustomPropertyEditorRegistrar:
package utils import grails.util.GrailsConfig; import java.text.SimpleDateFormat; import org.springframework.beans.PropertyEditorRegistrar; import org.springframework.beans.PropertyEditorRegistry; /** * 注册自定义的属性装配器 * @author TZ * */ class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar { @Override public void registerCustomEditors(PropertyEditorRegistry registry) { def formats = GrailsConfig.get("grails.date.formats", List.class)?:["yyyy-MM-dd HH:mm:ss","yyyy-MM-dd'T'HH:mm:ss","yyyy-MM-dd"]; registry.registerCustomEditor(Date.class, new CustomDateBinder(formats)); } }
3)在conf/spring/resources.groovy中注册:
beans = { bean { //自定义属性绑定 customPropertyEditorRegistrar(utils.CustomPropertyEditorRegistrar) } }
4)conf/Config.groovy中添加配置:
grails.date.formats = ["yyyy-MM-dd HH:mm:ss","yyyy-MM-dd'T'HH:mm:ss","yyyy-MM-dd","yyyy-MM-dd HH:mm:ss.SSS ZZZZ", "dd.MM.yyyy HH:mm:ss"];