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

}
(0)

相关推荐

  • Windows10 微软输入法快速输入时间的格式

    Windows10 微软输入法快速输入时间的格式

  • Java常用的时间工具类DateTimeUtils.java对常用的时间操作方法总结

    话不多少,直接上代码!时间工具类DateTimeUtils.java 汇总了以前常用的时间操作方法! 工具类方法列表: 将 String 转为 date 日期字符串格式化输出 Date类型日期转字符串 ...

  • Java泛型——泛型矩阵类

    Java泛型--泛型矩阵类 所有矩阵,加法和乘法操作都是类似,所以设计一个父类,不用管元素类型,目的描述所有类型的矩阵共享的通用操作 创建若干适用于指定矩阵类型的子类,实例:两种类型int和Ratio ...

  • 修改职业清单、审查EOI打分、缩短偏远移民时间...这类移民职业继续改革!189仍有机会,新州州担是优选!

    工程移民 澳洲技术移民职业清单的400多个职业中,工程无疑是其中的大户之一,这个行业也是澳洲的关键行业,可以申请豁免入境. 另外,本财年的EOI邀请中,除了医护健康类,主要也就工程类发了189和491 ...

  • Java高并发16-LongAdder类源码解析(下)

    一.复习 上次连载简单的介绍了其他函数的作用以及功能 二.完整的LongAdder类源码 package com.ruigege.AtomicOperationClass4;import java.u ...

  • Java学习——38、类的抽象性

    抽象是研究复杂对象的基本方法,从复杂对象中抽象出本质特征,忽略次要细节,使某些信息和实现对于使用者不可见.抽象层次越高,其软件利用程序越高. 1.抽象类 使用关键字abstract声明的类为抽象类. ...

  • Java学习——37、类的多态(二)

    类型的多态主要体现在:子类是一种父类类型. 子类通过继承扩充和发展了它的父类,子类是父类的一种特殊类型. 1.子类对象即是父类对象 子类对象包含了父类的所有成员,包括成员变量和成员方法,所以子类对象也 ...

  • Java学习——36、类的多态(一)

    多态性是指"一种定义,多种实现".例如,画画.同是画画,但每一个人,会画出来不同的画,这就是多态. 多态主要有方法的多态和类型的多态. 今天介绍方法的多态. 方法的多态包括方法的重 ...

  • Java学习——34、类的继承

    面向对象四大特性:封装.继承.多态.抽象. 今天介绍继承. 继承是面向对象的核心特性,能够最大限度地实现代码复用. 1.  由继承派生类 继承允许在已有类的基础上创建新类. 创建的新类叫做子类(或派生 ...

  • Java学习_Java核心类

    字符串和编码 字符串在String内部是通过一个char[]数组表示的,因此,可以按下面的写法: String s2 = new String(new char[] {'H', 'e', 'l', ' ...