话不多说,请看代码:
DateUtil.java
package pers.kangxu.datautils.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
import pers.kangxu.datautils.common.exception.DefineException;
public class DateUtil {
public static Date strToDate(String strDate,String dateFormat){
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Date date = null;
try {
date = sdf.parse(strDate);
} catch (Exception e) {
throw new DefineException("日期格式转换出错");
}
return date;
}
public static String dateToStr(Date date,String tarDateFormat){
return new SimpleDateFormat(tarDateFormat).format(date);
}
public static String strToStr(String strDate,String srcFormat,String tarFormat){
SimpleDateFormat sdf = new SimpleDateFormat(srcFormat);
try {
Date date = sdf.parse(strDate);
sdf = new SimpleDateFormat(tarFormat);
strDate = sdf.format(date);
} catch (Exception e) {
throw new DefineException("日期格式转换出错");
}
return strDate;
}
}
测试使用
DateUtilTester.java
package pers.kangxu.datautils.test;
import java.util.Date;
import pers.kangxu.datautils.utils.DateUtil;
public class DateUtilTester {
public static void main(String[] args) {
System.out.println(DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:dd"));
System.out.println(DateUtil.strToStr("2011-1-1 1:1:1","yyyy-MM-dd HH:mm:ss", "yyyyMMddHHmmss"));
System.out.println(DateUtil.strToDate("2011-1-1 1:1:1","yyyy-MM-dd HH:mm:ss"));
}
}
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持考高分网!



