-、方式一
1、字符串转时间
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") private Date startTime;
2、字符串转时间亦可以,这个加载controller控制层即可
@InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
3、时间转字符串
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
private Date startTime;
二、方式二(序列化)
JsonSerialize:时间为字符串格式
JsonDeserialize :字符串转时间
@JsonSerialize(using = JsonDateSerializer$19.class) @JsonDeserialize(using = JsonDateDeserializer$19.class) private Date updateTime;
package com.ppfuns.mediaasset.core.common; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.map.JsonSerializer; import org.codehaus.jackson.map.SerializerProvider; import org.springframework.stereotype.Component; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; @Component public class JsonDateSerializer$19 extends JsonSerializer{ SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Override public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { String formattedDate = formatter.format(value); jgen.writeString(formattedDate); } }
package com.ppfuns.mediaasset.core.common; import org.apache.commons.lang.StringUtils; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.map.DeserializationContext; import org.codehaus.jackson.map.JsonDeserializer; import java.io.IOException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * TODO: 字符串转时间格式为yyyy-MM-dd HH:mm:ss * * @author jiandequn * @date 2014-6-24 上午10:07:19 * @version 0.1.0 * @copyright yougou.com */ public class JsonDateDeserializer$19 extends JsonDeserializer{ private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Override public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { String str = jp.getText().trim(); if (StringUtils.isEmpty(str)) { return null; } try { return formatter.parse(str); } catch (ParseException e) { e.printStackTrace(); return null; } } }
MAVEN依赖的包
3 7org.codehaus.jackson 4jackson-mapper-asl 5${jackson.version} 68 12com.fasterxml.jackson.core 9jackson-core 10${jackson.core.version} 1113 17 18 19com.fasterxml.jackson.core 14jackson-databind 15${jackson.core.version} 1620 1.9.13 212.4.2 22