栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Grails日期解组

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Grails日期解组

最干净的方法可能是为可能的日期格式注册自定义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 / spring / 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"]


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/636724.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号