日期工具类(ThreadLocal)模式

package com.haowu.partner.base.util;


import org.apache.commons.lang3.StringUtils;

import java.text.DateFormat;

import org.apache.commons.lang3.StringUtils;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User:tangzhouqi
 * Date:2018/5/9
 * Time:17:27
 * 类或接口实现功能描述
 */
public class DateUtils {
    /** 锁对象 */
    private static final Object lockObj = new Object();
    public static final String YYYYMMDD_HHMMSS = "yyyy-MM-dd HH:mm:ss";
    public static final String YYYY_MM_DD = "yyyy-MM-dd";

    /** 存放不同的日期模板格式的sdf的Map */
    private static Map> sdfMap = new HashMap>();
    private static ThreadLocal local = new ThreadLocal();
    public static final String DEFAULT_FORMAT = "yyyy-MM-dd";


    /**
     * 返回一个ThreadLocal的sdf,每个线程只会new一次sdf
     */
    private static SimpleDateFormat getSdf(final String pattern) {
        ThreadLocal thread1 = sdfMap.get(pattern);

        // 此处的双重判断和同步是为了防止sdfMap这个单例被多次put重复的sdf
        if (thread1 == null) {
            synchronized (lockObj) {
                thread1 = sdfMap.get(pattern);
                if (thread1 == null) {
                    // 只有Map中还没有这个pattern的sdf才会生成新的sdf并放入map
                    // 这里是关键,使用ThreadLocal替代原来直接new SimpleDateFormat
                    thread1 = new ThreadLocal() {
                        @Override
                        protected SimpleDateFormat initialValue() {
                            return new SimpleDateFormat(pattern);
                        }
                    };
                    sdfMap.put(pattern, thread1);
                }
            }
        }
        return thread1.get();
    }

    /**
     * 比较日期是否相等,年月日
     *
     * @param d1
     * @param d2
     * @return
     */
    public static boolean sameDate(Date d1, Date d2) {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
        return fmt.format(d1).equals(fmt.format(d2));
    }

    public static String formatDate(Date datestr) {
        if (datestr != null) {
            String pattern = "yyyy-MM-dd";
            try {
                return getSdf(pattern).format(datestr);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } else {
            return "";
        }
    }

    public static String formatTime(Date datestr) {
        if (datestr != null) {
            String pattern = "yyyy-MM-dd HH:mm:ss";
            try {
                return getSdf(pattern).format(datestr);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } else {
            return null;
        }
    }

    public static String formatDate(Date datestr, String pattern) {
        if (datestr != null) {
            try {
                return getSdf(pattern).format(datestr);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 获取今年年份
     * @return
     */
    public static Integer getNowYear(Date date) {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy");
        return Integer.valueOf(fmt.format(date));
    }

    /**
     * 获取某年第一天日期
     * @param year 年份
     * @return Date
     */
    public static Date getYearFirst(int year){
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        Date currYearFirst = calendar.getTime();
        return currYearFirst;
    }


    /**
     * 获取某年最后一天
     * @return
     */
    public static Date getLastDayOfMonth(Date date ) throws ParseException {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy");
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR,Integer.valueOf(sdf1.format(date)));
        //设置月份
        cal.set(Calendar.MONTH, 11);
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        //设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String lastDayOfMonth = sdf.format(cal.getTime());
        java.util.Date beginDate= sdf.parse(lastDayOfMonth);
        return beginDate;
    }
    /**
     * 是否是最后一天
     * @return
     */
    public static boolean isLastDay(Date date) throws ParseException {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy");
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR,Integer.valueOf(sdf1.format(date)));
        //设置月份
        cal.set(Calendar.MONTH, 11);
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        //设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String lastDate = sdf.format(cal.getTime());
        if (lastDate.equals(sdf.format(date))){
            return true;
        }
        return false;
    }

    /**
     * 是否是第一天
     * @throws
     */
    public static boolean isFirstDay( Date date)throws ParseException {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy");

        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR,Integer.valueOf(sdf1.format(date)));
        //设置月份
        cal.set(Calendar.MONTH, 0);
        //获取某月最小天数
        int firstDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
        //设置日历中月份的最小天数
        cal.set(Calendar.DAY_OF_MONTH, firstDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String firstDate = sdf.format(cal.getTime());
        if (firstDate.equals(sdf.format(date))){
            return true;
        }
        return false;
    }


    /** 功能描述:时间相减得到天数
      * @param beginDt
      * @param endDt
      * @return
        6      * long
      * @author Administrator
      */
    public static int getDaySub(Date beginDt,Date endDt) {
         int rtday =0;
         try{
             java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd");
             java.util.Date beginDate= format.parse(format.format(beginDt));
             java.util.Date endDate= format.parse(format.format(endDt));
             Long day = (endDate.getTime()- beginDate.getTime())/(24*60*60*1000);
             rtday = day.intValue();
             System.out.println("相隔的天数="+day);
         } catch (ParseException e){
                 // TODO 自动生成 catch 块
                 e.printStackTrace();
         }
         return rtday;
    }

    /**
      * 指定日期加上天数后的日期
      */
     public static Date plusDay(int num,Date newDate ) throws ParseException{
         Calendar cal = Calendar.getInstance();
         cal.setTime(newDate);//设置起时间
         cal.add(Calendar.DATE, num);//增加一天
      return cal.getTime();
     }

    /**
     * 指定时间加 分钟
     */
    public static Date plusMinutes(int minutes, Date time) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.add(Calendar.MINUTE, minutes);
        return calendar.getTime();
    }



    /***
     * --发布时间显示规则:

     1.列表加载时间-发布时间 小于 1分钟,显示“刚刚发布”

     2.列表加载时间-发布时间 大于等于 1分钟 小于 60分钟,显示“x分钟前”  x=【列表加载时间-发布时间】取整(分)

     3.列表加载时间-发布时间 大于等于 1小时 小于 24小时,显示“x小时前”  x=【列表加载时间-发布时间】取整(小时)

     4.列表加载时间-发布时间 大于等于 24小时 小于 240小时,显示“x天前”  x=【列表加载时间-发布时间】取整(天)

     5.列表加载时间-发布时间 大于等于 240小时,显示“发布日期”
     * @param publishDate
     * @return
     */
    public static String getPublishDateStr(Date publishDate){
        if (publishDate != null){

            //分钟
            Double t = ((double)((new Date()).getTime()- publishDate.getTime()))/(60*1000);
            int minute = t.intValue();
            if (minute < 1){
                return "刚刚发布";
            }
            if (minute >= 1 && minute < 60){
                return minute +"分钟前";
            }

            //小时
            t = ((double)((new Date()).getTime()- publishDate.getTime()))/(60*60*1000);
            minute = t.intValue();
            if (minute >= 1 && minute < 24){
                return minute +"小时前";
            }
            //一天
            t = ((double)((new Date()).getTime() - publishDate.getTime()))/(60*60*24*1000);
            minute = t.intValue();
            if (minute >= 1 && minute < 10){
                return minute +"天前";
            }
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            return dateFormat.format(publishDate);
        }
        return null;
    }

    public static Date dateFormat(String dateStr){
        //注意:SimpleDateFormat构造函数的样式与strDate的样式必须相符
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
       // SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //加上时间
        //必须捕获异常
        try {
            Date date=simpleDateFormat.parse(dateStr);
            System.out.println(date);
            return date;
        } catch(ParseException px) {
            px.printStackTrace();
        }
        return null;
    }


    public static Date timeFormat(String timeStr){
        String pattern = "yyyy-MM-dd HH:mm:ss";
        if (StringUtils.isNotBlank(timeStr)) {
            try {
                Date time = getSdf(pattern).parse(timeStr);
                System.out.println(time);
                return time;
            } catch (ParseException px) {
                px.printStackTrace();
                return null;
            }
        } else {
            return null;
        }
    }

    public static Date timeFormat(String timeStr, String pattern){
        if (StringUtils.isNotBlank(timeStr)) {
            try {
                Date time = getSdf(pattern).parse(timeStr);
                System.out.println(time);
                return time;
            } catch (ParseException px) {
                px.printStackTrace();
                return null;
            }
        } else {
            return null;
        }
    }


    /**
     * 格式化Date
     * @param date
     * @param format
     * @return
     */
    public static String parseDateToStr(Date date, String format){
        try{
            if(format==null){
                format = DEFAULT_FORMAT;
            }
            if(date!=null){
                DateFormat dateFormat=new SimpleDateFormat(format);
                return dateFormat.format(date);
            }else{
                return null;
            }

        }catch (Exception e){
            return null;
        }
    }

    /**
     *格式化String
     * @param str
     * @param format
     * @return
     */
    public static Date parseStrToDate(String str, String format){
        try{
            if(format==null){
                format = DEFAULT_FORMAT;
            }
            if(str!=null){
                DateFormat dateFormat=new SimpleDateFormat(format);
                return dateFormat.parse(str);
            }else{
                return null;
            }

        }catch (Exception e){
            return null;
        }
    }

    /**
     * 判断两个日期是否为同一天
     * @param date1
     * @param date2
     * @return
     */
    public static boolean isSameDay(Date date1, Date date2){
        if(date1 != null && date2 != null){
            Calendar cal1 = Calendar.getInstance();
            cal1.setTime(date1);
            Calendar cal2 = Calendar.getInstance();
            cal2.setTime(date2);
            return cal1.get(0) == cal2.get(0) && cal1.get(1) == cal2.get(1) && cal1.get(6) == cal2.get(6);
        }else{
            return false;
        }

    }


    public static void main(String[] args){

        System.out.println(getDateDiff(new Date(),parseStrToDate("2019-09-9 19:06","yyyy-MM-dd HH:mm"),Calendar.MINUTE));

    }






    public static Date localParse(String DateStr, String pattern) throws Exception {
        SimpleDateFormat sdf = local.get();
        if (sdf == null) {
            sdf = new SimpleDateFormat(pattern, Locale.US);
            local.set(sdf);
        }
        return sdf.parse(DateStr);
    }
    /**
     * 功能描述:格式化时间后,得到 endDt 减 beginDt 的秒数
     * rtSeconds >0 : endDt > beginDt
     * @param beginDt
     * @param endDt
     * @return Integer
     *
     */
    public static Integer getSecondSub(Date beginDt, Date endDt, String formatStr) {
        int rtSeconds = 0;
        if (StringUtils.isBlank(formatStr)) {
            formatStr = YYYY_MM_DD;
        }
        try {
            SimpleDateFormat format = new SimpleDateFormat(formatStr);
            Date beginDate = format.parse(format.format(beginDt));
            Date endDate = format.parse(format.format(endDt));
            Long day = (endDate.getTime() - beginDate.getTime()) / (1000);
            rtSeconds = day.intValue();
        } catch (ParseException e) {
            return null;
        }
        return rtSeconds;
    }

    /**
     * 时间相差值
     * @param d1
     * @param d2
     * @param field
     * @return
     */
    public static Long getDateDiff(Date d1,Date d2, int field){
        Long difference = d1.getTime()-d2.getTime();
        Long diff = null;
        switch (field){
            case Calendar.DATE: diff = difference/(3600*24*1000);break;
            case Calendar.HOUR: diff = difference/(3600*1000);break;
            case Calendar.MINUTE: diff = difference/(60*1000);break;
            case Calendar.SECOND: diff = difference/1000;break;
        }
        return diff;
    }


    /** 功能描述:日期比较,前者是否小于后者
     * @param beginDt
     * @param endDt
     * @return
     * @Author: 001214
     */
    public static boolean isExpired(Date beginDt, Date endDt) {
        try{
            SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
            String beginDate = f.format(beginDt);
            String endDate = f.format(endDt);
            if (Integer.valueOf(beginDate).intValue() < Integer.valueOf(endDate).intValue()){
                return true;
            }
        } catch (Exception e){
            // TODO 自动生成 catch 块
            e.printStackTrace();
        }
        return false;
    }
}


你可能感兴趣的:(多线程专栏)