日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

【Java】TimeFormatUtils(時間格式化工具類)

 Coder編程 2021-07-06

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;
        }
    }

}

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多