The example resolves the Java date format utility class DateUtil.java
- 2020-05-27 05:25:19
- OfStack
Without further ado, look at the code:
DateUtil.java
package pers.kangxu.datautils.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
import pers.kangxu.datautils.common.exception.DefineException;
/**
*
* <b>
* Processing date Utility class
* </b>
* @author kangxu
*
*/
public class DateUtil {
/**
* String date to date format date
* @param str String date
* @param dateFormat String date format
* @return
*/
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(" Date format conversion error ");
}
return date;
}
/**
* Converts a date to a string date
* @param date The date of
* @param tarDateFormat The date format
* @return
*/
public static String dateToStr(Date date,String tarDateFormat){
return new SimpleDateFormat(tarDateFormat).format(date);
}
/**
* Convert date format
* @param strDate String date
* @param srcFormat The original format
* @param tarFormat Target format
* @return
*/
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(" Date format conversion error ");
}
return strDate;
}
}
Test using
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"));
}
}