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)
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值