前台jsp用的一个日期插件,后台获取一直有问题。 被这个问题搞了好久,其实很简单。记录下来,希望可以帮到遇到同样问题的同学。 我项目使用的ssm框架, 在做web开发的时候,页面传入的都是String类型,SpringMVC可以对一些基本的类型进行转换,但是对于日期类的转换可能就需要我们配置。 1、如果查询类是我们自己写,那么在属性前面加上@DateTimeFormat(pattern = "yyyy-MM-dd") ,即可将String转换为Date类型,如下 @DateTimeFormat(pattern = "yyyy-MM-dd") private Date createTime; 2、如果我们只负责web层的开发,就需要在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));
//true:允许输入空值,false:不能为空值
3、可以在系统中加入一个全局类型转换器实现转换器,新建一个controller
public class DateConverter implements Converter<String, Date> {
@Override
public Date convert(String source) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
try {
return dateFormat.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
在springmvc配置文件中进行配置:
<bean id="conversionService" class="org.springframework.format.support.
FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.doje.XXX.web.DateConverter" />
</list>
</property>
</bean>
<mvc:annotation-driven conversion-service="conversionService" />
我使用了第三种方式,但在运行的时候报错,最后发现是DateConverter类中的日期转换有问题, debug发现前台传过来的是一串数字,猜测应该是毫秒,然后就在DateConverter类中将接受的source先进行了毫秒转成日期格式的时间,在进行转换结果没报错但日期还是不对,最后猜测前台传过来的应该是秒,debug将穿过来的日期记下来,用计算器转换发现确实是秒(这日期插件 --!!!一开始没想到传过来的时间是秒..算是个坑吧!)。问题找到了,剩下的就是日期转换的问题了(
/**
* 秒转换为指定格式的日期
*
* @param second
* @param patten
* @return Date类型
* @throws ParseException
*/
public synchronized static Date secondToDate(long second,
String patten) throws
ParseException {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(second * 1000);// 转换为毫秒
Date date = calendar.getTime();
SimpleDateFormat formatter = new SimpleDateFormat(patten);
String dateString = formatter.format(date);
// ParsePosition pos = new ParsePosition(8);
Date currentTime = formatter.parse(dateString);
return currentTime;
}
/**
* 秒转换为指定格式的日期
*
* @param second
* @param patten
* @return String类型
*/
public synchronized static String secondToDateString(long second,
String patten)
{
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(second * 1000);// 转换为毫秒
Date date = calendar.getTime();
SimpleDateFormat format = new SimpleDateFormat(patten);
String dateString = format.format(date);
return dateString;
}
/**
* 返回日时分秒
*
* @param second
* @return
*/
public synchronized static String secondToTime(long second) {
long days = second / 86400;// 转换天数
second = second % 86400;// 剩余秒数
long hours = second / 3600;// 转换小时数
second = second % 3600;// 剩余秒数
long minutes = second / 60;// 转换分钟
second = second % 60;// 剩余秒数
if (0 < days) {
return days + "天," + hours + "小时," +minutes +
"分,"+second+ "秒";
} else {
return hours + "小时," + minutes + "分," +
second + "秒";
}
}
好了,基本就是这样了。这个问题关键在于前台传过来的居然是秒,搞了半天....