Java工具集-日期(DateUtils)

本文介绍了作者为解决日常开发中频繁使用工具类的需求,而创建的一个不依赖外部库的Java日期工具类DateUtils。遵循不依赖JDK以外的源码和每个类独立解耦的原则,使得开发者可以方便地复制单个类到项目中直接使用,避免引入额外依赖带来的问题。邀请社区成员共同参与,贡献各自实用的工具类。
摘要由CSDN通过智能技术生成

简单工具类

写作初衷:由于日常开发经常需要用到很多工具类,经常根据需求自己写也比较麻烦
网上好了一些工具类例如commom.lang3或者hutool或者Jodd这样的开源工具,但是
发现他们之中虽然设计不错,但是如果我想要使用,就必须要引入依赖并且去维护依赖,有些
甚至会有存在版本编译不通过问题,故此想要写作一个每个类都可以作为独立工具类使用
每个使用者只需要复制该类,到任何项目当中都可以使用,所以需要尊从以下两个原则才能
做到.在此诚邀各位大佬参与.可以把各自用过的工具,整合成只依赖JDK,每个类都能够单独
使用的工具.每个人当遇到业务需求需要使用的时候,只需要到这里单独拷贝一个即可使用.
抛弃传统的需要引入依赖的烦恼.让大家一起来解决你所面临的业务问题吧!

介绍

遵从两大原则

  • 1.绝不依赖JDK以外的源码
  • 2.牺牲代码复用性,每个类都必须是单独的组件,绝不互相引用,做到完全解耦
package *;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.TimeZone;

/**
 * @program: simple_tools
 * @description:
 * @author: ChenWenLong
 * @create: 2019-06-04 16:19
 **/
public class DateUtils {
   

    //无时区的格式化
    public static final FastDateFormat ISO_DATETIME_FORMAT
            = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss");
    //带时区的格式化
    public static final FastDateFormat ISO_DATETIME_TIME_ZONE_FORMAT
            = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ssZZ");
    //纯日期格式化
    public static final FastDateFormat ISO_DATE_FORMAT
            = FastDateFormat.getInstance("yyyy-MM-dd");
    //带时区的日期格式化
    public static final FastDateFormat ISO_DATE_TIME_ZONE_FORMAT
            = FastDateFormat.getInstance("yyyy-MM-ddZZ");
    //不带时区的时间格式化
    public static final FastDateFormat ISO_TIME_FORMAT
            = FastDateFormat.getInstance("'T'HH:mm:ss");
    //带时区的时间格式化
    public static final FastDateFormat ISO_TIME_TIME_ZONE_FORMAT
            = FastDateFormat.getInstance("'T'HH:mm:ssZZ");
    //没有T前缀的,非ISO8601规范的时间格式化
    public static final FastDateFormat ISO_TIME_NO_T_FORMAT
            = FastDateFormat.getInstance("HH:mm:ss");
    //带时区的,非ISO8601规范的时间格式化
    public static final FastDateFormat ISO_TIME_NO_T_TIME_ZONE_FORMAT
            = FastDateFormat.getInstance("HH:mm:ssZZ");
    public static final FastDateFormat SMTP_DATETIME_FORMAT
            = FastDateFormat.getInstance("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US);
    private static String[] parsePatterns = {
   
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
    //世界时间格式
    public static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("GMT");
    //每秒=1000毫秒
    public static final long MILLIS_PER_SECOND = 1000;
    //每分钟=60秒
    public static final long MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND;
    //每小时=60分钟
    public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE;
    //每天=24小时
    public static final long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR;
    //表示半个月,这个表示是上半旬还是下半旬
    public final static int SEMI_MONTH = 1001;

    public final static int RANGE_WEEK_SUNDAY = 1;
    public final static int RANGE_WEEK_MONDAY = 2;
    public final static int RANGE_WEEK_RELATIVE = 3;
    public final static int RANGE_WEEK_CENTER = 4;
    public final static int RANGE_MONTH_SUNDAY = 5;
    public final static int RANGE_MONTH_MONDAY = 6;

    private static final int[][] fields = {
   
            {
   Calendar.MILLISECOND},
            {
   Calendar.SECOND},
            {
   Calendar.MINUTE},
            {
   Calendar.HOUR_OF_DAY, Calendar.HOUR},
            {
   Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.AM_PM},
            {
   Calendar.MONTH, SEMI_MONTH},
            {
   Calendar.YEAR},
            {
   Calendar.ERA}};

    /**
     * 功能描述:
     * 〈判断是否是同一天,接受Date类型〉
     *
     * @params : [date1, date2]
     * @return : boolean
     * @author : cwl
     * @date : 2019/6/6 11:00
     */
    public static boolean isSameDay(Date date1, Date date2) {
   
        if (date1 == null || date2 == null) {
   
            throw new IllegalArgumentException("The date must not be null");
        }
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        return isSameDay(cal1, cal2);
    }

    /**
     * 功能描述:
     * 〈判断是否是同一天,接受Calendar〉
     *
     * @params : [cal1, cal2]
     * @return : boolean
     * @author : cwl
     * @date : 2019/6/6 11:01
     */
    public static boolean isSameDay(Calendar cal1, Calendar cal2) {
   
        if (cal1 == null || cal2 == null) {
   
            throw new IllegalArgumentException("The date must not be null");
        }
        return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&
                cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
                cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR));
    }

    /**
     * 功能描述:
     * 〈判断是否是同一时间,接受Date类型〉
     *
     * @params : [date1, date2]
     * @return : boolean
     * @author : cwl
     * @date : 2019/6/6 11:02
     */
    public static boolean isSameTime(Date date1, Date date2) {
   
        if (date1 == null || date2 == null) {
   
            throw new IllegalArgumentException("The date must not be null");
        }
        return date1.getTime() == date2.getTime();
    }

    /**
     * 功能描述:
     * 〈判断是否是同一时间,接受Calendar〉
     *
     * @params : [cal1, cal2]
     * @return : boolean
     * @author : cwl
     * @date : 2019/6/6 11:03
     */
    public static boolean isSameTime(Calendar cal1, Calendar cal2) {
   
        if (cal1 == null || cal2 == null) {
   
            throw new IllegalArgumentException("The date must not be null");
        }
        return cal1.getTime().getTime() == cal2.getTime().getTime();
    }

    /**
     * 功能描述:
     * 〈是否是同一地区是时间,即将二手Calendar类型.Date类型并没有地区这种说法〉
     *
     * @params : [cal1, cal2]
     * @return : boolean
     * @author : cwl
     * @date : 2019/6/6 11:07
     */
    public static boolean isSameLocalTime(Calendar cal1, Calendar cal2) {
   
        if (cal1 == null || cal2 == null) {
   
            throw new IllegalArgumentException("The date must not be null");
        }
        return (cal1.get(Calendar.MILLISECOND) == cal2.get(Calendar.MILLISECOND) &&
                cal1.get(Calendar.SECOND) == cal2.get(Calendar.SECOND) &&
                cal1.get(Calendar.MINUTE) == cal2.get(Calendar.MINUTE) &&
                cal1.get(Calendar.HOUR) == cal2.get(Calendar.HOUR) &&
                cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) &&
                cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
                cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&
                cal1.getClass() == cal2.getClass());
    }

    /**
     * 功能描述:
     * 〈尝试用不同的格式去格式化字符串日期〉
     *
     * @params : [str, parsePatterns]
     * @return : java.util.Date
     * @author : cwl
     * @date : 2019/6/6 11:19
     */
    public static Date parseDate(String str, String[] parsePatterns) throws ParseException {
   
        if (str == null || parsePatterns == null) {
   
            throw new IllegalArgumentException("Date and Patterns must not be null");
        }

        SimpleDateFormat parser = null;
        ParsePosition pos = new ParsePosition(0);
        for (int i = 0; i < parsePatterns.length; i++) {
   
            if (i == 0) {
   
                parser = new SimpleDateFormat(parsePatterns[0]);
            } else {
   
                parser.applyPattern(parsePatterns[i]);
            }
            pos.setIndex(0);
            Date date = parser.parse(str, pos);
            if (date != null && pos.getIndex() == str.length()) {
   
                return date;
            }
        }
        throw new ParseException("Unable to parse the date: " + str, -1);
    }

    /**
     * 功能描述:
     * 〈解析时间格式〉
     *
     * @params : [str]
     * @return : java.util.Date
     * @author : cwl
     * @date : 2019/10/17 16:47
     */
    public static Date parseDate(Object str) {
   
        if (str == null) {
   
            return null;
        }
        try {
   
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
   
            return null;
        }
    }

    /**
     * 功能描述:
     * 〈加amount年〉
     *
     * @params : [date, amount]
     * @return : java.util.Date
     * @author : cwl
     * @date : 2019/6/6 11:22
     */
    public static Date addYears(Date date, int amount) {
   
        return add(date, Calendar.YEAR, amount);
    }

    /**
     * 功能描述:
     * 〈加amount月〉
     *
     * @params : [date, amount]
     * @return : java.util.Date
     * @author : cwl
     * @date : 2019/6/6 11:22
     */
    public static Date addMonths(Date date, int amount) {
   
        return add(date, Calendar.MONTH, amount);
    }

    /**
     * 功能描述:
     * 〈加amount月〉
     *
     * @params : [date, amount]
     * @return : java.util.Date
     * @author : cwl
     * @date : 2019/6/6 11:23
     */
    public static Date addWeeks(Date date, int amount) {
   
        return add(date, Calendar.WEEK_OF_YEAR, amount);
    }

    /**
     * 功能描述:
     * 〈加amount天〉
     *
     * @params : [date, amount]
     * @return : java.util.Date
     * @author : cwl
     * @date : 2019/6/6 11:23
     */
    public static Date addDays(Date date, int amount) {
   
        return add(date, Calendar.DAY_OF_MONTH, amount);
    }

    /**
     * 功能描述:
     * 〈标准格式化时间.传入毫秒数mills和pattern格式〉
     *
     * @params : [millis, pattern]
     * @return : java.lang.String
     * @author : cwl
     * @date : 2019/6/5 17:29
     */
    public static String formatUTC(long millis, String pattern) {
   
        return format(new Date(millis), pattern, UTC_TIME_ZONE, null);
    }

    /**
     * 功能描述:
     * 〈加amount小时〉
     *
     * @params : [date, amount]
     * @return : java.util.Date
     * @author : cwl
     * @date : 2019/6/6 11:24
     */
    public static Date addHours(Date date, int amount) {
   
        return add(date, Calendar.HOUR_OF_DAY, amount);
    }


    /**
     * 功能描述:
     * 〈标准格式化时间,传入date时间格式,pattern格式〉
     *
     * @params : [date, pattern]
     * @return : java.lang.String
     * @author : cwl
     * @date : 2019/6/5 17:30
     */
    public static String formatUTC(Date date, String pattern) {
   
        return format(date, pattern, UTC_TIME_ZONE, null);
    }

    /**
     * 功能描述:
     * 〈加amount分钟〉
     *
     * @params : [date, amount]
     * @return : java.util.Date
     * @author : cwl
     * @date : 2019/6/6 11:24
     */
    public static Date addMinutes(Date date, int amount) {
   
        return add(date, Calendar.MINUTE, amount);
    }

    /**
     * 功能描述:
     * 〈加amount秒〉
     *
     * @params : [date, amount]
     * @return : java.util.Date
     * @author : cwl
     * @date : 2019/6/6 11:24
     */
    public static Date addSeconds(Date date, int amount) {
   
        return add(date, Calendar.SECOND, amount);
    }

    /**
     * 功能描述:
     * 〈加amount毫秒〉
     *
     * @params : [date, amount]
     * @return : java.util.Date
     * @author : cwl
     * @date : 2019/6/6 11:33
     */
    public static Date addMilliseconds(Date date, int amount) {
   
        return add(date, Calendar.MILLISECOND, amount);
    }

    /**
     * 功能描述:
     * 〈添加年/月/日/时/分/秒/毫秒 amount为添加量〉
     *
     * @params : [date, calendarField, amount]
     * @return : java.util.Date
     * @author : cwl
     * @date : 2019/6/6 11:34
     */
    public static Date add(Date date, int calendarField, int amount) {
   
        if (date == null) {
   
            throw new IllegalArgumentException("The date must not be null");
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(calendarField, amount);
        return c.getTime();
    }

    /**
     * 功能描述:
     * 〈设置date年份,并返回一个新的日期〉
     *
     * @params : [date, amount]
     * @return : java.util.Date
     * @author : cwl
     * @date : 2019/6/6 11:35
     */
    public static Date setYears(Date date, int amount) {
   
        return set(date, Calendar.YEAR, amount);
    }

    /**
     * 功能描述:
     * 〈设置date月份,返回一个新的日期〉
     *
     * @params : [date, amount]
     * @return : java.util.Date
     * @author : cwl
     * @date : 2019/6/6 11:36
     */
    public static Date setMonths(Date date, int amount) {
   
        return set(date, Calendar.MONTH, amount);
    }

    /**
     * 功能描述:
     * 〈设置date日期,返回一个新的日期〉
     *
     * @params : [date, amount]
     * @return : java.util.Date
     * @author : cwl
     * @date : 2019/6/6 11:37
     */
    public static Date setDays(Date date, int amount) {
   
        return set(date, Calendar.DAY_OF_MONTH, amount);
    }

    /**
     * 功能描述:
     * 〈设置时间,返回一个新的时间〉
     *
     * @params : [date, amount]
     * @return : java.util.Date
     * @author : cwl
     * @date : 2019/6/6 11:38
     */
    public static Date setHours(Date date, int amount) {
   
        return set(date, Calendar.HOUR_OF_DAY, amount);
    }

    /**
     * 功能描述:
     * 〈设置时间,返回一个新的时间〉
     *
     * @params : [date, amount]
     * @return : java.util.Date
     * @author : cwl
     * @date : 2019/6/6 11:38
     */
    public static Date setMinutes(Date date, int amount) {
   
        return set(date, Calendar.MINUTE, amount);
    }

    /**
     * 功能描述:
     * 〈设置时间,返回一个新的时间〉
     *
     * @params : [date, amount]
     * @return : java.util.Date
     * @author : cwl
     * @date : 2019/6/6 11:39
     */
    public static Date setSeconds(Date date, int amount) {
   
        return set(date, Calendar.SECOND, amount);
    }

    /**
     * 功能描述:
     * 〈设置时间,返回一个新的时间〉
     *
     * @params : [date, amount]
     * @return : java.util.Date
     * @author : cwl
     * @date : 2019/6/6 11:39
     */
    public static Date setMilliseconds(Date date, int amount) {
   
        return set(date, Calendar.MILLISECOND, amount);
    }

    /**
     * 功能描述:
     * 〈设置时间〉
     *
     * @params : [date, calendarField, amount]
     * @return : java.util.Date
     * @author : cwl
     * @date : 2019/6/6 11:40
     */
    private static Date set(Date date, int calendarField, int amount) {
   
        if (date == null) {
   
            throw new IllegalArgumentException("The date must not be null");
        }
        // getInstance() returns a new object, so this method is thread safe.
        Calendar c = Calendar.getInstance();
        c.setLenient(false);
        c.setTime(date);
        c.set(calendarField, amount);
        return c.getTime();
    }

    /**
     * 功能描述:
     * 〈对日期Date类型进行四舍五入〉
     *
     * @params : [date, field]
     * @return : java.util.Date
     * @author : cwl
     * @date : 2019/6/6 13:58
     */
    public static Date round(Date date, int field) {
   
        if (date == null) {
   
            throw new IllegalArgumentException("The date must not be null");
        }
        Calendar gval = Calendar.getInstance();
        gval.setTime(date);
        modify(gval, field, true);
        return gval.getTime();
    }

    /**
     * 功能描述:
     * 〈对日历类Calander类型进行四舍五入〉
     *
     * @params : [date, field]
     * @return : java.util.Calendar
     * @author : cwl
     * @date : 2019/6/6 13:58
     */
    public static Calendar round(Calendar date, int field) {
   
        if (date == null) {
   
            throw new IllegalArgumentException("The date must not be null");
        }
        Calendar rounded = (Calendar) date.clone();
        modify(rounded, field, true);
        return rounded;
    }

    /**
     * 功能描述:
     * 〈对Date类型或者Calendar类型进行四舍五入〉
     *
     * @params : [date, field]
     * @return : java.util.Date
     * @author : cwl
     * @date : 2019/6/6 14:02
     */
    public static Date round(Object date, int field) {
   
        if (date == null) {
   
            throw new IllegalArgumentException("The date must not be null");
        }
        if (date instanceof Date) {
   
            return round((Date) date, field);
        } else if (date instanceof Calendar) {
   
            return round((Calendar) date, field).getTime();
        } else {
   
            throw new ClassCastException("Could not round " + date);
        }
    }

    /**
     * 功能描述:
     * 〈截断日期,例如可以对分钟数进行取整截断,或者对小时进行取整截断,或者对秒数取整截断.仅接受日期类Date〉
     *
     * @params : [date, field]
     * @return : java.util.Date
     * @author : cwl
     * @date : 2019/6/6 14:04
     */
    public static Date truncate(Date date, int field) {
   
        if (date == null) {
   
            throw new IllegalArgumentException("The date must not be null");
        }
        Calendar gval = Calendar.getInstance();
        gval.setTime(date);
        modify(gval, field, false);
        return gval.getTime();
    }

    /**
     * 功能描述:
     * 〈截断日期,例如可以对分钟数进行取整截断,或者对小时进行取整截断,或者对秒数取整截断.仅接受日历类Calendar〉
     *
     * @params : [date, field]
     * @return : java.util.Calendar
     * @author : cwl
     * @date : 2019/6/6 14:06
     */
    public static Calendar 
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值