Without further ado, please see 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> * Date processing tool 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; } /** * Convert date to string date* @param date date* @param tarDateFormat 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 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 usage
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")); }}The above is all the content of this article. I hope that the content of this article will be of some help to everyone’s study or work. I also hope to support Wulin.com more!