java 简单的时间日期格式工具类
原创    forever    发表于:2017-08-02 16:36:28
  阅读 :126   收藏   编辑
  • 定义类型
import java.io.Serializable;

/**
 * <p>
 * 日期格式化类型
 * </p>
 * 
 */
public enum DateStyleEnum  {

    yyyymmdd("0", "yyyyMMdd"), yyyy_mm_dd_hh_mm_ss("1", "yyyy-MM-dd HH:mm:ss"),yyyy_MM_dd("2","yyyy-MM-dd");

    private final Serializable key;

    private final Serializable value;


    private DateStyleEnum( Serializable key, Serializable value ) {
        this.key = key;
        this.value = value;
    }


    public Serializable key() {
        return key;
    }


    public Serializable value() {
        return value;
    }

}
  • 日期格式化工具类
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtil {

    /**
     * Date -> String
     * @param date
     * @param pattern
     * @return
     */
    public static String dateFormat(Date date,DateStyleEnum pattern) {
        if (date == null) date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat(pattern.value().toString());
        return sf.format(date);
    }


    /**
     * String -> Date 
     * @param date
     * @param pattern
     * @return
     * @throws Exception
     */
    public static Date formatDate(String date,DateStyleEnum pattern) throws Exception {
        if (date == null) throw new Exception("dataFormat date str is null ");
        SimpleDateFormat sf = new SimpleDateFormat(pattern.value().toString());
        return sf.parse(date);
    }


    /**
     * Test
     * @param args
     */
    public static void main(String[] args) throws Exception {
        System.out.println(dateFormat(new Date(), DateStyleEnum.yyyy_mm_dd_hh_mm_ss));
        System.out.println(formatDate("2017-08-02 16:29:56", DateStyleEnum.yyyy_mm_dd_hh_mm_ss));
    }

}
评论
条评论