`
javamail
  • 浏览: 39690 次
  • 性别: Icon_minigender_1
  • 来自: 江西
社区版块
存档分类
最新评论

Grails 日期操作

阅读更多
一、在Config.groovy中增加(你要转的时间格式)
    grails.date.formats = ["yyyy-MM-dd HH:mm:ss","yyyy-MM-dd HH:mm","yyyy-MM-dd'T'HH:mm:ss","yyyy-MM-dd","yyyy-MM-dd HH:mm:ss.SSS ZZZZ", "dd.MM.yyyy HH:mm:ss","yyyy-MM"]

二、增加日期转换类,放在Groovy源包中(CustomPropertyEditorRegistrar,CustomDateBinder)

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));
}
}


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
}
}
}
}

三、将注册的日期类写到spring/resource配置文件中
// Place your Spring DSL code here
beans = {
    bean {
        //自定义属性绑定
        customPropertyEditorRegistrar(utils.CustomPropertyEditorRegistrar)
    }
}
分享到:
评论
1 楼 331875787 2012-04-05  
whfdhg fdtu5fd fd hjsda  drtu guofx

相关推荐

Global site tag (gtag.js) - Google Analytics