DateFormatUtil.java 1.99 KB
package com.meishu.util;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Locale;

/**
 * 处理时间工具
 *
 * @author DengMin
 * @date 2019/08/27 13:56
 **/
public class DateFormatUtil {

    public final static String YEAR = "yyyy";
    public final static String FMT_sdf14_L = "yyyy-MM-dd HH:mm:ss";
    public final static String FMT_sdf_yMd = "yyyy-MM-dd";
    public final static String FMT_sdf_yM = "yyyy-M";
    public final static String FMT_sdf_yMM = "yyyy-MM";
    public final static String FMT_sdf_Hm = "H:mm";
    public final static String FMT_sdf_HHmm = "HH:mm";
    public final static String cron = "s m H d M ? yyyy";

    /**
     * Date转String,自定义格式
     * @param date
     * @param pattern
     * @return
     */
    public static String format(Date date, String pattern) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            return sdf.format(date);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * String转Date,自定义格式
     * @param date
     * @param pattern
     * @return
     */
    public static Date parse(String date, String pattern) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            return sdf.parse(date);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 比较两个时间
     * .after 大于
     * .before 小于
     * @param d1
     * @param d2
     * @return
     */
    public static boolean compare(Date d1, Date d2 ) {
        if(d1.after(d2)) {
            return false;
        }
        return true;
    }

    /**
     * Data转Cron
     * @param date
     * @return
     */
    public static String getCron(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("s m H d M ? yyyy");
        return sdf.format(date);
    }
}