在日常的工作中date和string的相互转化比较常用,下面介绍一个工具了:
maven的导包如下:
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.3</version>
</dependency>
DateTimeUntil工具类:
package com.mmall.until;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.util.Date;
/**
* Created by Administrator on 2017/10/12.
*/
public class DateTimeUntil {
//jidaTime
//String->Date
//Date->String
public static final String STANDRAD_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static Date strToDate(String DateTimeStr,String formaStr){
DateTimeFormatter dateTimeFormat = DateTimeFormat.forPattern(formaStr);
DateTime dateTime = dateTimeFormat.parseDateTime(DateTimeStr);
return dateTime.toDate();
}
public static String dateToStr(Date date,String formaStr){
if (date==null){
return StringUtils.EMPTY;
}
DateTime dateTime = new DateTime(date);
return dateTime.toString(formaStr);
}
//为了方便应用,重载的函数
public static Date strToDate(String DateTimeStr){
DateTimeFormatter dateTimeFormat = DateTimeFormat.forPattern(STANDRAD_FORMAT);
DateTime dateTime = dateTimeFormat.parseDateTime(DateTimeStr);
return dateTime.toDate();
}
public static String dateToStr(Date date){
if (date==null){
return StringUtils.EMPTY;
}
DateTime dateTime = new DateTime(date);
return dateTime.toString(STANDRAD_FORMAT);
}
}
测试结果如下:
应用场景:构建viewObject
productDetailVo.setCreatetime(DateTimeUntil.dateToStr(product.getCreateTime()));
productDetailVo.setUpdatetime(DateTimeUntil.dateToStr(product.getUpdateTime()));