记录一下,方便以后查询调用
package com.savinghappy.util;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.util.Date;
/**
* Created by Saving on 2017/6/12.
* 用于String和Datetime之间的相互转换
*/
public class DateTimeUtil
{
private static final String DATA_FORMATSTRING="yyyy-MM-dd HH:mm:ss";
private DateTimeUtil()
{
}
/**
* 根据传进来的dataTimeStr和转换的格式formatStr来返回转回后的date
* @param dataTimeStr
* @param formatStr
* @return
*/
public static Date stringToDate(String dataTimeStr , String formatStr)
{
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(formatStr);
DateTime dateTime = dateTimeFormatter.parseDateTime(dataTimeStr);
return dateTime.toDate();
}
/**
* 根据传进来的data和转换的格式formatStr来返回转回后的date
* @param date
* @param formatStr
* @return
*/
public static String dateToString(Date date ,String formatStr)
{
if (date==null)return StringUtils.EMPTY;
return new DateTime(date).toString(formatStr);
}
/**
*根据传进来的dataTimeStr和转换的格式DATA_FORMATSTRING来返回转回后的date
* @param dataTimeStr
* @return
*/
public static Date stringToDate(String dataTimeStr)
{
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(DATA_FORMATSTRING);
DateTime dateTime = dateTimeFormatter.parseDateTime(dataTimeStr);
return dateTime.toDate();
}
/**
* 根据传进来的data和转换的格式DATA_FORMATSTRING来返回转回后的date
* @param date
* @return
*/
public static String dateToString(Date date)
{
if (date==null)return StringUtils.EMPTY;
return new DateTime(date).toString(DATA_FORMATSTRING);
}
}