1.Domain转换为Json简单,直接在bootstrap的init里面添加:
JsON.registerObjectMarshaller(Date) { return it?.format("yyyy-MM-dd HH:mm:ss")}
ps:还有一种方法是利用插件,重写Date的toString方法.
参见:http://stackoverflow.com/questions/690370/how-to-return-specific-date-format-as-json-in-grails
2.Js段提交数据到controller,自动转换为DATE.
1)在src/groovy添加:
package utilsimport 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 utilsimport 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","yyyy-MM-dd HH:mm:ss.SSS ZZZZ","dd.MM.yyyy HH:mm:ss"];总结
以上是内存溢出为你收集整理的Grails时间类型自动转换的格式设置(in/out)全部内容,希望文章能够帮你解决Grails时间类型自动转换的格式设置(in/out)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)