【Java】TimeFormatUtils(时间格式化工具类)

Java 时间格式化工具类

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

public enum TimeFormatUtils {

    /** 日期格式 <code>[yyyy-MM-dd]</code> */
    DATE("yyyy-MM-dd"),
    
    /** 日期格式 <code>[yyyyMMdd]</code> */
    DATE_COMPACT("yyyyMMdd"),
    
    /** 日期格式 <code>[yyyy_MM_dd]</code> */
    DATE_UNDERLINE("yyyy_MM_dd"),
    
    /** 时间格式 <code>[HH:mm:ss]</code> */
    TIME("HH:mm:ss"),
    
    /** 时间格式 <code>[HHmmss]</code> */
    TIME_COMPACT("HHmmss"),
    
    /** 时间格式 <code>[HH_mm_ss]</code> */
    TIME_UNDERLINE("HH_mm_ss"),
    
    /** 时间格式 <code>[HH:mm:ss.SSS]</code> */
    TIME_MILLI("HH:mm:ss.SSS"),
    
    /** 时间格式 <code>[HHmmssSSS]</code> */
    TIME_MILLI_COMPACT("HHmmssSSS"),
    
    /** 时间格式 <code>[HH_mm_ss_SSS]</code> */
    TIME_MILLI_UNDERLINE("HH_mm_ss_SSS"),
    
    /** 日期时间格式 <code>[yyyy-MM-dd HH:mm:ss]</code> */
    DATE_TIME("yyyy-MM-dd HH:mm:ss"),
    
    /** 日期时间格式 <code>[yyyyMMddHHmmss]</code> */
    DATE_TIME_COMPACT("yyyyMMddHHmmss"),
    
    /** 日期时间格式 <code>[yyyy_MM_dd_HH_mm_ss]</code> */
    DATE_TIME_UNDERLINE("yyyy_MM_dd_HH_mm_ss"),
    
    /** 日期时间格式 <code>[yyyy-MM-dd HH:mm:ss.SSS]</code> */
    DATE_TIME_MILLI("yyyy-MM-dd HH:mm:ss.SSS"),
    
    /** 日期时间格式 <code>[yyyyMMddHHmmssSSS]</code> */
    DATE_TIME_MILLI_COMPACT("yyyyMMddHHmmssSSS"),
    
    /** 日期时间格式 <code>[yyyy_MM_dd_HH_mm_ss_SSS]</code> */
    DATE_TIME_MILLI_UNDERLINE("yyyy_MM_dd_HH_mm_ss_SSS");
    

    // --------------------------------------------------------------------------------------------

    
    private final SimpleDateFormat formatter;
    
    private TimeFormatUtils(String pattern) {
        this.formatter = new SimpleDateFormat(pattern);
    }
    
    private static class CacheHolder {
        private static final int CAPACITY = 8;
        private static final Map<String, SimpleDateFormat> CACHE = 
                new LinkedHashMap<String, SimpleDateFormat>(CAPACITY, 1F, true) {
                    private static final long serialVersionUID = -929434365574586032L;
                    @Override
                    protected boolean removeEldestEntry(Map.Entry<String, SimpleDateFormat> eldest) {
                        return size() >= (CAPACITY - 1);
                    }
                };
    }
    

    // --------------------------------------------------------------------------------------------

    
    /**
     * Formats a date-time object using this formatter. 
     * 
     * @return  the formatted string, not null
     */
    public String now() {
        synchronized (formatter) {
            return formatter.format(new Date());
        }
    }
    
    /**
     * Formats a date-time object using this formatter. 
     * 
     * @param epochSecond
     * @return  the formatted string, not null
     */
    public String formatEpochSecond(long epochSecond) {
        synchronized (formatter) {
            return formatter.format(new Date(epochSecond * 1000L));
        }
    }
    
    /**
     * Formats a date-time object using this formatter. 
     * 
     * @param epochMilli
     * @return  the formatted string, not null
     */
    public String formatEpochMilli(long epochMilli) {
        synchronized (formatter) {
            return formatter.format(new Date(epochMilli));
        }
    }
    
    /**
     * Formats a date-time object using this formatter. 
     * 
     * @param date
     * @return  the formatted string, not null
     */
    public String formatDate(Date date) {
        synchronized (formatter) {
            return formatter.format(date);
        }
    }
    

    // --------------------------------------------------------------------------------------------

    
    /**
     * Fully parses the text producing an object of the specified type.
     * 
     * @param date
     * @return  the parsed time-stamp
     */
    public long parseEpochSecond(String date) {
        synchronized (formatter) {
            try {
                return formatter.parse(date).getTime() / 1000L;
            } catch (ParseException e) {
                // throw new DateTimeParseException(e.getMessage(), date, e.getErrorOffset());
                throw new RuntimeException("Text '" + date + "' could not be parsed at index " + e.getErrorOffset());
            }
        }
    }
    
    /**
     * Fully parses the text producing an object of the specified type.
     * 
     * @param date
     * @return  the parsed time-stamp
     */
    public long parseEpochMilli(String date) {
        synchronized (formatter) {
            try {
                return formatter.parse(date).getTime();
            } catch (ParseException e) {
                // throw new DateTimeParseException(e.getMessage(), date, e.getErrorOffset());
                throw new RuntimeException("Text '" + date + "' could not be parsed at index " + e.getErrorOffset());
            }
        }
    }
    
    /**
     * Fully parses the text producing an object of the specified type.
     * 
     * @param date
     * @return  the parsed date-time, not null
     */
    public Date parseDate(String date) {
        synchronized (formatter) {
            try {
                return formatter.parse(date);
            } catch (ParseException e) {
                // throw new DateTimeParseException(e.getMessage(), date, e.getErrorOffset());
                throw new RuntimeException("Text '" + date + "' could not be parsed at index " + e.getErrorOffset());
            }
        }
    }
    

    // --------------------------------------------------------------------------------------------

    
    /**
     * Adds to a date returning a new object.
     * The original date object is unchanged.
     *
     * @param date  the date, not null
     * @param calendarField  the calendar field to add to
     * @param amount  the amount to add, may be negative
     * @return the new date object with the amount added
     */
    private Date add(Date date, int calendarField, int amount) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(calendarField, amount);
        return c.getTime();
    }
    
    /**
     * Adds a number of years to a date returning a new object.
     * The original date object is unchanged.
     *
     * @param date  the date, not null
     * @param amount  the amount to add, may be negative
     * @return the new date object with the amount added
     * @throws IllegalArgumentException if the date is null
     */
    public Date addYears(Date date, int amount) {
        synchronized (formatter) {
            return add(date, Calendar.YEAR, amount);
        }
    }
    
    /**
     * Adds a number of months to a date returning a new object.
     * The original date object is unchanged.
     *
     * @param date  the date, not null
     * @param amount  the amount to add, may be negative
     * @return the new date object with the amount added
     * @throws IllegalArgumentException if the date is null
     */
    public Date addMonths(Date date, int amount) {
        synchronized (formatter) {
            return add(date, Calendar.MONTH, amount);
        }
    }
    
    /**
     * Adds a number of weeks to a date returning a new object.
     * The original date object is unchanged.
     *
     * @param date  the date, not null
     * @param amount  the amount to add, may be negative
     * @return the new date object with the amount added
     * @throws IllegalArgumentException if the date is null
     */
    public Date addWeeks(Date date, int amount) {
        synchronized (formatter) {
            return add(date, Calendar.WEEK_OF_YEAR, amount);
        }
    }
    
    /**
     * Adds a number of days to a date returning a new object.
     * The original date object is unchanged.
     *
     * @param date  the date, not null
     * @param amount  the amount to add, may be negative
     * @return the new date object with the amount added
     * @throws IllegalArgumentException if the date is null
     */
    public Date addDays(Date date, int amount) {
        synchronized (formatter) {
            return add(date, Calendar.DAY_OF_MONTH, amount);
        }
    }
    
    /**
     * Adds a number of hours to a date returning a new object.
     * The original date object is unchanged.
     *
     * @param date  the date, not null
     * @param amount  the amount to add, may be negative
     * @return the new date object with the amount added
     * @throws IllegalArgumentException if the date is null
     */
    public Date addHours(Date date, int amount) {
        synchronized (formatter) {
            return add(date, Calendar.HOUR_OF_DAY, amount);
        }
    }
    
    /**
     * Adds a number of minutes to a date returning a new object.
     * The original date object is unchanged.
     *
     * @param date  the date, not null
     * @param amount  the amount to add, may be negative
     * @return the new date object with the amount added
     * @throws IllegalArgumentException if the date is null
     */
    public Date addMinutes(Date date, int amount) {
        synchronized (formatter) {
            return add(date, Calendar.MINUTE, amount);
        }
    }
    
    /**
     * Adds a number of seconds to a date returning a new object.
     * The original date object is unchanged.
     *
     * @param date  the date, not null
     * @param amount  the amount to add, may be negative
     * @return the new date object with the amount added
     * @throws IllegalArgumentException if the date is null
     */
    public Date addSeconds(Date date, int amount) {
        synchronized (formatter) {
            return add(date, Calendar.SECOND, amount);
        }
    }
    
    /**
     * Adds a number of milliseconds to a date returning a new object.
     * The original date object is unchanged.
     *
     * @param date  the date, not null
     * @param amount  the amount to add, may be negative
     * @return the new date object with the amount added
     * @throws IllegalArgumentException if the date is null
     */
    public Date addMilliseconds(Date date, int amount) {
        synchronized (formatter) {
            return add(date, Calendar.MILLISECOND, amount);
        }
    }
    

    // --------------------------------------------------------------------------------------------

    
    /**
     * Adds a number of years to a date returning a new object.
     * The original date object is unchanged.
     *
     * @param date  the date, not null
     * @param amount  the amount to add, may be negative
     * @return the new date object with the amount added
     * @throws IllegalArgumentException if the date is null
     */
    public String addYears(String date, int amount) {
        synchronized (formatter) {
            try {
                return formatter.format(add(formatter.parse(date), Calendar.YEAR, amount));
            } catch (ParseException e) {
                // throw new DateTimeParseException(e.getMessage(), date, e.getErrorOffset());
                throw new RuntimeException("Text '" + date + "' could not be parsed at index " + e.getErrorOffset());
            }
        }
    }
    
    /**
     * Adds a number of months to a date returning a new object.
     * The original date object is unchanged.
     *
     * @param date  the date, not null
     * @param amount  the amount to add, may be negative
     * @return the new date object with the amount added
     * @throws IllegalArgumentException if the date is null
     */
    public String addMonths(String date, int amount) {
        synchronized (formatter) {
            try {
                return formatter.format(add(formatter.parse(date), Calendar.MONTH, amount));
            } catch (ParseException e) {
                // throw new DateTimeParseException(e.getMessage(), date, e.getErrorOffset());
                throw new RuntimeException("Text '" + date + "' could not be parsed at index " + e.getErrorOffset());
            }
        }
    }
    
    /**
     * Adds a number of weeks to a date returning a new object.
     * The original date object is unchanged.
     *
     * @param date  the date, not null
     * @param amount  the amount to add, may be negative
     * @return the new date object with the amount added
     * @throws IllegalArgumentException if the date is null
     */
    public String addWeeks(String date, int amount) {
        synchronized (formatter) {
            try {
                return formatter.format(add(formatter.parse(date), Calendar.WEEK_OF_YEAR, amount));
            } catch (ParseException e) {
                // throw new DateTimeParseException(e.getMessage(), date, e.getErrorOffset());
                throw new RuntimeException("Text '" + date + "' could not be parsed at index " + e.getErrorOffset());
            }
        }
    }
    
    /**
     * Adds a number of days to a date returning a new object.
     * The original date object is unchanged.
     *
     * @param date  the date, not null
     * @param amount  the amount to add, may be negative
     * @return the new date object with the amount added
     * @throws IllegalArgumentException if the date is null
     */
    public String addDays(String date, int amount) {
        synchronized (formatter) {
            try {
                return formatter.format(add(formatter.parse(date), Calendar.DAY_OF_MONTH, amount));
            } catch (ParseException e) {
                // throw new DateTimeParseException(e.getMessage(), date, e.getErrorOffset());
                throw new RuntimeException("Text '" + date + "' could not be parsed at index " + e.getErrorOffset());
            }
        }
    }
    
    /**
     * Adds a number of hours to a date returning a new object.
     * The original date object is unchanged.
     *
     * @param date  the date, not null
     * @param amount  the amount to add, may be negative
     * @return the new date object with the amount added
     * @throws IllegalArgumentException if the date is null
     */
    public String addHours(String date, int amount) {
        synchronized (formatter) {
            try {
                return formatter.format(add(formatter.parse(date), Calendar.HOUR_OF_DAY, amount));
            } catch (ParseException e) {
                // throw new DateTimeParseException(e.getMessage(), date, e.getErrorOffset());
                throw new RuntimeException("Text '" + date + "' could not be parsed at index " + e.getErrorOffset());
            }
        }
    }
    
    /**
     * Adds a number of minutes to a date returning a new object.
     * The original date object is unchanged.
     *
     * @param date  the date, not null
     * @param amount  the amount to add, may be negative
     * @return the new date object with the amount added
     * @throws IllegalArgumentException if the date is null
     */
    public String addMinutes(String date, int amount) {
        synchronized (formatter) {
            try {
                return formatter.format(add(formatter.parse(date), Calendar.MINUTE, amount));
            } catch (ParseException e) {
                // throw new DateTimeParseException(e.getMessage(), date, e.getErrorOffset());
                throw new RuntimeException("Text '" + date + "' could not be parsed at index " + e.getErrorOffset());
            }
        }
    }
    
    /**
     * Adds a number of seconds to a date returning a new object.
     * The original date object is unchanged.
     *
     * @param date  the date, not null
     * @param amount  the amount to add, may be negative
     * @return the new date object with the amount added
     * @throws IllegalArgumentException if the date is null
     */
    public String addSeconds(String date, int amount) {
        synchronized (formatter) {
            try {
                return formatter.format(add(formatter.parse(date), Calendar.SECOND, amount));
            } catch (ParseException e) {
                // throw new DateTimeParseException(e.getMessage(), date, e.getErrorOffset());
                throw new RuntimeException("Text '" + date + "' could not be parsed at index " + e.getErrorOffset());
            }
        }
    }
    
    /**
     * Adds a number of milliseconds to a date returning a new object.
     * The original date object is unchanged.
     *
     * @param date  the date, not null
     * @param amount  the amount to add, may be negative
     * @return the new date object with the amount added
     * @throws IllegalArgumentException if the date is null
     */
    public String addMilliseconds(String date, int amount) {
        synchronized (formatter) {
            try {
                return formatter.format(add(formatter.parse(date), Calendar.MILLISECOND, amount));
            } catch (ParseException e) {
                // throw new DateTimeParseException(e.getMessage(), date, e.getErrorOffset());
                throw new RuntimeException("Text '" + date + "' could not be parsed at index " + e.getErrorOffset());
            }
        }
    }
    

    // --------------------------------------------------------------------------------------------

    
    /**
     * Change the format of the date display
     * 
     * @param date      date of the String type
     * @param pattern   the format of the date display
     * @return
     */
    public String transform(String date, String pattern) {
        synchronized (CacheHolder.CACHE) {
            if (CacheHolder.CACHE.containsKey(pattern)) {
                return CacheHolder.CACHE.get(pattern).format(parseDate(date));
            }
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            String result = sdf.format(parseDate(date));
            if (pattern.length() == result.length()) {
                CacheHolder.CACHE.putIfAbsent(pattern, sdf);
            }
            return result;
        }
    }

}
原文地址:https://www.cnblogs.com/zhuzhongxing/p/14147113.html