DateFormatUtil.java 2.21 KB
package com.subsidy.util;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;

/**
 * 处理时间工具
 *
 * @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 ) {
        return !d1.after(d2);
    }

    /**
     * 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);
    }

    public static Date localDateTimeToDate(LocalDateTime dateTime) {
        if(dateTime == null) {
            return null;
        }
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = dateTime.atZone(zoneId);
        return Date.from(zdt.toInstant());
    }
}