Groovy   发布时间:2022-04-12  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Grails时间类型自动转换的格式设置(in/out)大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

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 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","yyyy-MM-dd HH:mm:ss.SSS ZZZZ","dd.Mm.yyyy HH:mm:ss"];

大佬总结

以上是大佬教程为你收集整理的Grails时间类型自动转换的格式设置(in/out)全部内容,希望文章能够帮你解决Grails时间类型自动转换的格式设置(in/out)所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。