Java中的日期处理

简单介绍下java中日期处理时需要用到的几个类:Date、Calendar、SimpleDateFormat
几个概念:

  1. 时间戳
    时间戳指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。

Date类

类 Date 表示特定的瞬间,精确到毫秒。Date类中的很多方法都被废弃,比如对年月日时分秒等日期数据获取和操作都放在了Calendar中

常用方法

  1. boolean after(Date when)
    测试此日期是否在指定日期之后。
  2. boolean before(Date when)
    测试此日期是否在指定日期之前。
  3. Object clone()
    返回此对象的副本。
  4. int compareTo(Date anotherDate)
    比较两个日期的顺序。
  5. boolean equals(Object obj)
    比较两个日期的相等性。
  6. void setTime(long time)
    根据时间戳获取Date对象
  7. void setTime(long time)
    设置时间戳
  8. void getTime()
    获取时间戳

Calendar类

Calendar 类是一个抽象类,它为特定瞬间与一组诸如 YEAR、MONTH、DAY_OF_MONTH、HOUR 等 日历字段之间的转换提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法。瞬间可用毫秒值来表示,它是距历元(即格林威治标准时间 1970 年 1 月 1 日的 00:00:00.000,格里高利历)的偏移量。

该类还为实现包范围外的具体日历系统提供了其他字段和方法。这些字段和方法被定义为 protected。

与其他语言环境敏感类一样,Calendar 提供了一个类方法 getInstance,以获得此类型的一个通用的对象。Calendar 的 getInstance 方法返回一个 Calendar 对象,其日历字段已由当前日期和时间初始化

常用方法

  1. abstract void add(int field, int amount)
    根据日历的规则,为给定的日历字段添加或减去指定的时间量。
    例如,要从当前日历时间减去 5 天,可以通过调用以下方法做到这一点:
    add(Calendar.DAY_OF_MONTH, -5);
  2. public boolean after(Object when)
    判断此 Calendar 表示的时间是否在指定 Object 表示的时间之后,返回判断结果。此方法等效于:
    when instanceof Calendar && compareTo((Calendar)when) > 0;//Calendar源码
    即当且仅当 when 是一个 Calendar 实例时,且“compareTo((Calendar)when) > 0”true时,after方法才返回 true。否则该方法返回 false。
  3. public boolean before(Object when)
    判断此 Calendar 表示的时间是否在指定 Object 表示的时间之前,返回判断结果。此方法等效于:
    return when instanceof Calendar && compareTo((Calendar)when) < 0;
    即当且仅当 when 是一个 Calendar 实例时,且“compareTo((Calendar)when) < 0”返回true时,after方法才返回 true。否则该方法返回 false。
  4. int get(int field)
    注意事项:
    Calendar用0表示一月份;
    HOUR_OF_DAY表示24进制,HOUR表示AM或者PM的小时,是十二进制表示;
    DAY_OF_WEEK从周日开始算起

    例如:
    System.out.println(“现在是”+now.get(Calendar.YEAR)+”年”);
    System.out.println(“现在是”+now.get(Calendar.MONTH)+”月”);
    System.out.println(“现在是”+now.get(Calendar.DAY_OF_MONTH)+”日”);
    System.out.println(“现在是”+now.get(Calendar.HOUR_OF_DAY)+”时”);
    System.out.println(“现在是”+now.get(Calendar.MINUTE)+”分”);
    System.out.println(“现在是”+now.get(Calendar.SECOND)+”秒”);
  5. public int getActualMaximum(int field)
    给定此 Calendar 的时间值,返回指定日历字段可能拥有的最大值。
  6. public static Calendar getInstance()
    使用默认时区和语言环境获得一个日历。返回的 Calendar 基于当前时间,使用了默认时区和默认语言环境。
  7. public final Date getTime()
    返回一个表示此 Calendar 时间值(从 历元至现在的毫秒偏移量)的 Date 对象。
  8. public long getTimeInMillis()
    返回此 Calendar 的时间值,以毫秒为单位。获取时间戳
  9. public final void clear()
    将此 Calendar 的所日历字段值和时间值(从 历元至现在的毫秒偏移量)设置成未定义。这意味着 isSet() 对于所有的日历字段都将返回 false,并且日期和时间计算会将这些字段作为从未设置的字段对待。 Calendar 实现类可能对日期/时间计算使用字段的特定默认值。例如,如果未定义 YEAR 字段值,则 GregorianCalendar 会使用 1970。
  10. 三个set方法
    void set(int year, int month, int date)
    设置日历字段 YEAR、MONTH 和 DAY_OF_MONTH 的值。
    void set(int year, int month, int date, int hourOfDay, int minute)
    设置日历字段 YEAR、MONTH、DAY_OF_MONTH、HOUR_OF_DAY 和 MINUTE 的 值。
    void set(int year, int month, int date, int hourOfDay, int minute, int second)
    设置字段 YEAR、MONTH、DAY_OF_MONTH、HOUR、MINUTE 和 SECOND 的值。
  11. public void setLenient(boolean lenient)
    指定日期/时间解释是否是宽松的。对于宽松的解释,可以将诸如 “February 942, 1996” 之类的日期视为等同于 1996 年 1 月 1 日后的第 941 天。而对于严格的(non-lenient)解释,这样的日期会导致抛出异常。默认情况下是宽松的。
  12. void setTime(Date date)
    使用给定的 Date 设置此 Calendar 的时间。
  13. void setTimeInMillis(long millis)
    用给定的 long 值设置此 Calendar 的当前时间值。

SimpleDateFormat类

日期和时间格式由日期和时间模式 字符串指定。在日期和时间模式字符串中,未加引号的字母 ‘A’ 到 ‘Z’ 和 ‘a’ 到 ‘z’ 被解释为模式字母,用来表示日期或时间字符串元素。文本可以使用单引号 (‘) 引起来,以免进行解释。
例子:

常用方法

  1. public SimpleDateFormat(String pattern)
    用给定的模式和默认语言环境的日期格式符号构造 SimpleDateFormat。
  2. String format(Date date)
    将一个 Date 格式化为日期/时间字符串。
  3. Date parse(String source)
    从给定字符串的开始解析文本,以生成一个日期。

公共方法类


import com.hikvision.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.util.SystemOutLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

public class DateUtil {

    private static Logger logger = LoggerFactory.getLogger(DateUtil.class);

    public static final String DEFAULT_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    public static final String DEFAULT_LASTDATETIME_FORMAT = "yyyy-MM-dd 23:59:59";

    public static final String DEFAULT_BGNDATETIME_FORMAT = "yyyy-MM-dd 00:00:00";

    public static final String DEFAULT_DATETIME24_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";

    private static final String DEFAULT_DATEMOBAN_FORMAT = "MM-dd HH:mm";

    private static final String DEFAULT_DATEFULLTIME_FORMAT = "yyyyMMddHHmmss";

    private static final long MILLISECONDS_A_DAY = 24 * 3600 * 1000;

    private static final long MILLISECONDS_A_HOUR = 3600 * 1000;

    private static final long MILLISECONDS_A_second = 1000;

    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";

    public static final String YEAR_MONTH_FORMAT = "yyyy/MM";

    public static final String DEFAULT_YEAR_MONTH_FORMAT1 = "yyyy-MM";

    private static final String MILLISECOND_FORMAT = "yyyyMMddHHmmssSSS";

    public static final String DEFAULT_DATEFULLDATE_FORMAT = "yyyyMMdd";

    public static final String DEFAULT_YEAR_MONTH_FORMAT = "yyyyMM";

    public static final String DEFAULT_YEAR_FORMAT = "yyyy";

    public static final String DEFAULT_MONTH_FORMAT = "MM";

    public static final String DEFAULT_Day_FORMAT = "dd";

    //验证日期字符串,有效日期范围1900-1-1到2099-12-31.
    private static final Pattern pattern = Pattern
            .compile("(?:(?:19|20)\\d{2})-(?:0?[1-9]|1[0-2])-(?:0?[1-9]|[12][0-9]|3[01])");


    /**
     * @return String
     * @Description:获取当前时间的30天后的时间
     */
    public static Date getPreMonth() {
        Date now = addDays(new Date(), 30);
        SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATETIME_FORMAT);
        Date afterMonth = null;
        try {
            afterMonth = format.parse(format.format(now.getTime()));
        } catch (ParseException e) {
            logger.error("解析日期失败:方法,getPreMonth()", e);
        }
        return afterMonth;
    }

    /**
     * @return String
     * @Description: 将时间转化格式为  yyyy-MM-dd HH:mm:ss 的字符串
     */
    public static String getDefaultTimeStr(Date date) {
        SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATETIME_FORMAT);
        return format.format(date);
    }

    /**
     * @return String
     * @Description: 将时间转化格式为  MM-dd HH:mm 的字符串
     */
    public static String getDefaultMOBANTimeStr(Date date) {
        SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATEMOBAN_FORMAT);
        return format.format(date);
    }


    /**
     * @return String
     * @Description: 将时间转化格式为  yyyy-MM-dd 23:59:59 的字符串
     */
    public static String getDefaultLastTimeStr(Date date) {
        SimpleDateFormat format = new SimpleDateFormat(DEFAULT_LASTDATETIME_FORMAT);
        return format.format(date);
    }

    /**
     * @return String
     * @Description: 将时间转化格式为  yyyy-MM-dd 00:00:00的字符串
     */
    public static String getDefaultBGNTimeStr(Date date) {

        SimpleDateFormat format = new SimpleDateFormat(DEFAULT_BGNDATETIME_FORMAT);
        return format.format(date);
    }

    /**
     * 将时间转化格式为  yyyy-MM-dd 的字符串
     * @param date
     * @return
     */
    public static String getDefaultTime2DateStr(Date date) {
        SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
        return format.format(date);
    }

    /**
     * 月份运算
     *
     * @param date    时间
     * @param amount  相加或相减的月份
     * @param pattern 时间格式
     * @return
     */
    public static Date gapMonth(Date date, int amount, String pattern) throws ParseException {
        Date endDate = DateUtils.addMonths(date, amount);
        Date overDate = DateUtils.parseDate(DateFormatUtils.format(endDate, pattern), DEFAULT_DATETIME_FORMAT);
        return overDate;
    }

    /**
     * 年份运算
     *
     * @param date    时间
     * @param amount  相加或相减的月份
     * @param pattern 时间格式
     * @return
     */
    public static Date gapYear(Date date, int amount, String pattern) throws ParseException {
        Date endDate = DateUtils.addYears(date, amount);
        Date overDate = DateUtils.parseDate(DateFormatUtils.format(endDate, pattern), DEFAULT_DATETIME_FORMAT);
        return overDate;
    }

    /**
     * 获取精确到秒的时间戳
     * @param date date
     * @return date为空则返回null
     */
    public static String getSecondTimestamp(Date date){
        if (null != date) {
            return String.valueOf(date.getTime()/1000);
        }
        return null;
    }


    /**
     * @return Date
     * @Description:当前时间加上days天
     */
    public static Date addDays(Date date, int days) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, days);
        return cal.getTime();
    }

    public static Date addMinutes(Date date, int minute) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MINUTE, minute);
        return cal.getTime();
    }
    //添加指定秒速
    public static Date addSecond(Date date, int second) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.SECOND, second);
        return cal.getTime();
    }

    public static Date parseDate(String s) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.parse(s);
    }
    public static Date parseDate(String s,String format) throws ParseException {
        if(StringUtil.isNullOrEmpty(format)){
            format = DEFAULT_DATE_FORMAT;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.parse(s);
    }

    /**
     * 按 yyyy-MM-dd HH:mm:ss 转换时间
     */
    public static Date parseDateFromStr(String s) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATETIME_FORMAT);
        return format.parse(s);
    }

    /**
     * 按 yyyyMMddHHmmss 转换时间
     */
    public static Date parseDateFromStrs(String s) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATEFULLTIME_FORMAT);
        return format.parse(s);
    }

    /**
     * 当前时间加上days月
     */
    public static Date addMonths(Date date, int months) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, months);
        return cal.getTime();
    }

    /**
     * 获取当前月的最大日期
     *
     * @return
     */
    public static Date getMaxDate() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));
        return cal.getTime();
    }

    /**
     * 获取当前年份
     *
     * @return
     */
    public static int getYear() {
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.YEAR);
    }

    /**
     * 获取当前月
     *
     * @return
     */
    public static int getMonth() {
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.MONTH) + 1;
    }

    /**
     * 获取当前月的最小日期
     *
     * @return
     */
    public static Date getMinDate() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DATE, cal.getActualMinimum(Calendar.DATE));
        return cal.getTime();
    }

    /**
     * 获取指定月的最小时间
     *
     * @param date
     * @return
     */
    public static Date getMinDateByMonth(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DATE, cal.getActualMinimum(Calendar.DATE));
        return cal.getTime();
    }

    /**
     * 获取指定月的最大时间
     *
     * @param date
     * @return
     */
    public static Date getMaxDateByMonth(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));
        return cal.getTime();
    }


    /**
     * 取得某月的的最后一天
     *
     * @param year
     * @param month
     * @return
     */
    public static Date getLastDayOfLastMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);// 年
        cal.set(Calendar.MONTH, month - 1);// 月,因为Calendar里的月是从0开始,所以要减1
        cal.set(Calendar.DATE, 1);// 日,设为一号
        cal.add(Calendar.DATE, -1);// 下一个月减一为本月最后一天
        return cal.getTime();// 获得月末是几号
    }

    /**
     * 当前时间加上years年
     */
    public static Date addYears(Date date, int years) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.YEAR, years);
        return cal.getTime();
    }

    /**
     * 获得指定格式的日期时间字符串
     *
     * @param format
     * @return
     */
    public static String datetime(String format) {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        return formatter.format(new Date());
    }

    /**
     * @return
     * @Description: 获取当天时间最后一秒(毫秒)
     */
    public static Date getEndTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = getCurrentDate() + " 23:59:59";
        Date time = null;
        try {
            time = formatter.parse(date);
        } catch (ParseException e) {
            logger.error("获取当天时间的结束时间: ", e);
        }
        return time;
    }

    /**
     * 获得指定格式的日期时间字符串
     *
     * @param date
     * @param format
     * @return
     */
    public static String datetime(Date date, String format) {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        return formatter.format(date);
    }

    /**
     * 获得指定格式的日期时间字符串
     *
     * @param date   日期字符串
     * @param format
     * @return
     */
    public static String datetime(String date, String format) {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        return formatter.format(date);
    }

    /**
     * 获得指定格式的当前日期字符串
     *
     * @param date
     * @param format
     * @return
     */
    public static String date(Date date, String format) {
        if (date == null) {
            return "";
        }

        return (new SimpleDateFormat(format)).format(date);
    }

    /**
     * 获得指定格式的当前日期字符串
     *
     * @param dateStr
     * @param format
     * @return
     */
    public static String date(String dateStr, String format) {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        return formatter.format(dateStr);
    }

    /**
     * 获得"yyyy-MM-dd"格式的当前日期字符串
     *
     * @return
     */
    public static String getNowDateStr() {
        return getNowDatetimeStr(DEFAULT_DATE_FORMAT);
    }

    /**
     * 获得"yyyy-MM-dd HH:mm:ss"格式的当前日期时间字符串
     *
     * @return
     */
    public static String getNowDatetimeStr() {
        return getNowDatetimeStr(DEFAULT_DATETIME_FORMAT);
    }

    /**
     * 获得"yyyyMMddHHmmss"格式的当前日期时间字符串
     *
     * @return
     */
    public static String getNowDateminStr() {
        return getNowDatetimeStr(DEFAULT_DATEFULLTIME_FORMAT);
    }

    /**
     * 将当前时间转成毫秒
     *
     * @return String
     */
    public static String getMillSecondStr() {
        Calendar cal = Calendar.getInstance();
        return datetime(cal.getTime(), MILLISECOND_FORMAT);
    }

    /**
     * 获得当前日期时间字符串
     *
     * @param format 日期格式
     * @return 日期时间字符串
     */
    public static String getNowDatetimeStr(String format) {
        Calendar cal = Calendar.getInstance();
        return datetime(cal.getTime(), format);
    }

    /**
     * 只取当前时间的日期部分,小时、分、秒等字段归零
     */
    public static Date dateOnly(Date date) {
        return new Date(date.getTime() / MILLISECONDS_A_DAY);
    }

    /**
     * 获取某个日期最大时间,yyyy-MM-dd 23:59:59
     * @param date
     * @return
     */
    public static Date dateMaxTime(Date date) {
        Date date1 = dateOnlyExt(date);
        Calendar c = Calendar.getInstance();
        c.setTime(date1);
        c.add(Calendar.DATE, 1);
        c.add(Calendar.SECOND, -1);
        date = c.getTime();
        return date;
    }

    /**
     * 只取当前时间的日期部分,小时、分、秒等字段归零
     */
    public static Date dateOnlyExt(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    /**
     * 只取当前时间的日期部分,小时、分、秒等字段归零
     */
    public static Date dateMinTime(Date date) {
        return dateOnlyExt(date);
    }

    /**
     * 把类似2007-2-2 7:1:8的时间串变为标准的2007-02-02 07:01:08
     *
     * @param dateTimeStr 未校正日期值
     * @return 日期对象
     */
    public static String getStandDateTimeStr(String dateTimeStr) {
        if (dateTimeStr == null || "".equals(dateTimeStr)) {
            return "";
        }

        dateTimeStr = dateTimeStr.replaceAll("\\s+", "|");
        String[] a = dateTimeStr.split("\\|");
        List<String> list = Arrays.asList(a);
        String datetime = "";
        int count = 1;
        for (int i = 0; i < list.size(); i++) {
            String temp = (String) list.get(i);
            StringTokenizer st;
            if (i == 0)
                st = new StringTokenizer(temp, "-");
            else
                st = new StringTokenizer(temp, ":");
            int k = st.countTokens();
            for (int j = 0; j < k; j++) {
                String sttemp = (String) st.nextElement();
                if (count == 1) {
                    datetime = sttemp;
                } else {
                    if ((sttemp.equals("0")) || (sttemp.equals("00")))
                        sttemp = "0";
                    else if ((Integer.valueOf(sttemp).intValue()) < 10)
                        sttemp = sttemp.replaceAll("0", "");
                    if (count < 4) {
                        if ((Integer.valueOf(sttemp).intValue()) < 10)
                            datetime = datetime + "-0" + sttemp;
                        else
                            datetime = datetime + "-" + sttemp;
                    }
                    if (count == 4) {
                        if ((Integer.valueOf(sttemp).intValue()) < 10)
                            datetime = datetime + " 0" + sttemp;
                        else
                            datetime = datetime + " " + sttemp;
                    }
                    if (count > 4) {
                        if ((Integer.valueOf(sttemp).intValue()) < 10)
                            datetime = datetime + ":0" + sttemp;
                        else
                            datetime = datetime + ":" + sttemp;
                    }
                }
                count++;
            }
        }

        try {
            @SuppressWarnings("unused")
            Date test = getDateFromStr(datetime); // 测试能否格式化成时间
            return datetime;
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 把标准的2007-02-02 07:01:08格式转换成日期对象
     *
     * @param datetime 日期,标准的2007-02-02 07:01:08格式
     * @return 日期对象
     */
    @SuppressWarnings("deprecation")
    public static Date getDateFromStr(String datetime) {
        if (datetime == null || "".equals(datetime)) {
            return new Date();
        }

        String nyr = datetime.trim();

        if (nyr.indexOf(" ") > 0) {
            nyr = nyr.substring(0, nyr.indexOf(" "));
        } else {
            nyr = nyr.substring(0, nyr.length());
        }

        StringTokenizer st = new StringTokenizer(nyr, "-");
        Date date = new Date();
        String temp = "";
        int count = st.countTokens();
        for (int i = 0; i < count; i++) {
            temp = (String) st.nextElement();
            // if(!(temp.equals("0")))
            // temp.replaceAll("0", "");
            if (i == 0)
                date.setYear(Integer.parseInt(temp) - 1900);
            if (i == 1)
                date.setMonth(Integer.parseInt(temp) - 1);
            if (i == 2)
                date.setDate(Integer.parseInt(temp));
        }

        if (datetime.length() > 10) {
            String sfm = datetime.substring(11, 19);
            StringTokenizer st2 = new StringTokenizer(sfm, ":");
            count = st2.countTokens();
            for (int i = 0; i < count; i++) {
                temp = (String) st2.nextElement();
                // if(!(temp.equals("0")))
                // temp.replaceAll("0", "");
                if (i == 0)
                    date.setHours(Integer.parseInt(temp));
                if (i == 1)
                    date.setMinutes(Integer.parseInt(temp));
                if (i == 2)
                    date.setSeconds(Integer.parseInt(temp));
            }
        }
        return date;
    }

    /**
     * 返回两个日期相差天数
     *
     * @param startDate 起始日期对象
     * @param endDate   截止日期对象
     * @return
     */
    public static int getQuot(Date startDate, Date endDate) {
        long quot = (endDate.getTime() - startDate.getTime()) / MILLISECONDS_A_DAY ;
        Long abs = Math.abs(quot);
        return abs.intValue();
    }

    /**
     * 返回两个日期相差天数
     *
     * @param startDateStr 起始日期字符串
     * @param endDateStr   截止期字符串
     * @param format       时间格式
     * @return
     */
    public static int getQuot(String startDateStr, String endDateStr,
                              String format) {
        long quot = 0;
        format = (format != null && format.length() > 0) ? format
                : DEFAULT_DATE_FORMAT;
        SimpleDateFormat ft = new SimpleDateFormat(format);
        try {
            Date date1 = ft.parse(endDateStr);
            Date date2 = ft.parse(startDateStr);
            quot = date1.getTime() - date2.getTime();
            quot = quot / MILLISECONDS_A_DAY;
        } catch (ParseException e) {
            logger.error("获取两个日期相差天数异常: ", e);
        }
        return (int) quot;
    }

    /**
     * 返回日期字符串:"yyyy-MM-dd HH:mm" 格式。
     *
     * @param date
     * @return
     */
    public static final String getDateTime(Date date) {
        if (date == null)
            return "";
        DateFormat ymdhmsFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return ymdhmsFormat.format(date);
    }

    /**
     * 按给定格式返回时间的字符串
     *
     * @param date
     * @param pattern
     * @return
     */
    public static final String getDateTime(Date date, String pattern) {
        if (date == null)
            return "";
        DateFormat ymdhmsFormat = new SimpleDateFormat(pattern);
        return ymdhmsFormat.format(date);
    }

    /**
     * 返回两个日期相差的小时
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static int getQuotHours(Date startDate, Date endDate) {
        long quot = 0;
        quot = endDate.getTime() - startDate.getTime();
        quot = quot / MILLISECONDS_A_HOUR;
        return (int) quot;
    }

    /**
     * 返回两个日期相差的秒数
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static int getQuotSeconds(Date startDate, Date endDate) {
        long quot = 0;
        quot = endDate.getTime() - startDate.getTime();
        quot = quot / MILLISECONDS_A_second;
        return (int) quot;
    }

    /**
     * 将字符串转换为日期型 格式为: yyyy-MM-dd
     *
     * @param dateTime
     * @return
     */
    public static Date getDateTime(String dateTime) {
        return getDateTime(dateTime, "yyyy-MM-dd");
    }

    /**
     * @param dateTime
     * @return
     * @Description: "yyyy-mm-dd hh24:mm:ss.fff";
     */
    public static Date getDate24Time(String dateTime) {
        return getDateTime(dateTime, DEFAULT_DATETIME24_FORMAT);
    }

    public static Date getDateTime(String dateTime, String formatPattern) {
        try {
            if (StringUtils.isNotBlank(dateTime)
                    && StringUtils.isNotBlank(formatPattern)) {
                SimpleDateFormat format = new SimpleDateFormat(formatPattern);
                return format.parse(dateTime);
            }
        } catch (ParseException e) {
            throw new BusinessException("解析日期失败!日期格式:" + formatPattern, e);
        }

        return null;
    }

    /**
     * 将字符串转换为日期型 格式为: yyyy-MM-dd HH:mm:ss
     *
     * @param dateTime
     * @return
     */
    public static Date getDateDetailTime(String dateTime) {
        try {
            if (StringUtils.isNotBlank(dateTime)) {
                SimpleDateFormat format = new SimpleDateFormat(
                        "yyyy-MM-dd HH:mm:ss");

                return format.parse(dateTime);
            }
        } catch (ParseException e) {
            logger.error("解析日期失败!", e);
        }

        return null;
    }

    /**
     * 取当前的时间戳,在页面上保证URL唯一,防止缓存
     *
     * @return
     */
    public static long getDtSeq() {
        return System.currentTimeMillis();
    }

    /**
     * 判断是否在参数日期的最大值和最小值之间
     *
     * @param min
     * @param compare
     * @return
     */
    public static boolean isBetween(Date min, Date compare) {
        Boolean ret = false;
        Date minDate = DateUtil.dateOnlyExt(min);
        Date maxDate = DateUtil.dateOnlyExt(DateUtil.addDays(min, 1));
        if (compare.after(minDate) && compare.before(maxDate)) {
            ret = true;
        }
        return ret;
    }

    /**
     * @param min
     * @param compare
     * @return
     * @Description: 比较2个时间的时间差
     */
    public static Long compare(Date min, Date compare) {
        return (compare.getTime() - min.getTime()) / 1000;
    }

    public static Date getDate(int year, int month, int day) {
        Calendar cal = Calendar.getInstance();
        cal.set(year, month - 1, day);
        return cal.getTime();
    }

    /**
     * 获取本月/上月/本季度的月初和月末.
     *
     * @param monthRange 取值范围{cm:本月,pm:上月,sm:本季度}
     * @return Map{firstDay:yyyy-MM-dd, lastDay:yyyy-MM-dd}
     */
    public static Map<String, String> getFLDayMap(String monthRange) {
        return getFLDayMap(monthRange, DEFAULT_DATE_FORMAT);
    }

    /**
     * 获取本月/上月/本季度的月初和月末.
     * @param monthRange 取值范围{cm:本月,pm:上月,sm:本季度}
     * @param pattern
     * @return Map{firstDay:yyyy-MM-dd, lastDay:yyyy-MM-dd}
     */
    public static Map<String, String> getFLDayMap(String monthRange,
                                                  String pattern) {
        Map<String, String> rs = new LinkedHashMap<String, String>();

        SimpleDateFormat df = new SimpleDateFormat(pattern);
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(new Date());

        if (StringUtils.isBlank(monthRange)) {
            monthRange = "cm";
        }

        if (!"sm".equals(monthRange)) {
            if ("pm".equals(monthRange)) {
                calendar.add(Calendar.MONTH, -1);
            }

            calendar.set(Calendar.DAY_OF_MONTH, 1);
            rs.put("firstDay", df.format(calendar.getTime()));

            calendar.set(Calendar.DAY_OF_MONTH,
                    calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            rs.put("lastDay", df.format(calendar.getTime()));

            return rs;
        }

        /*
         * 本季度的月初和月末
         */
        int[][] seasons = {{2, 4}, // 春季
                {5, 7}, // 夏季
                {8, 10}, // 秋季
                {11, 1} // 冬季
        };
        int cm = calendar.get(Calendar.MONTH) + 1;

        for (int[] im : seasons) {
            if (cm >= im[0] && cm <= im[1]) {
                calendar.set(Calendar.MONTH, im[0] - 1);
                calendar.set(Calendar.DAY_OF_MONTH, 1);
                rs.put("firstDay", df.format(calendar.getTime()));

                calendar.set(Calendar.MONTH, im[1] - 1);
                calendar.set(Calendar.DAY_OF_MONTH,
                        calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
                rs.put("lastDay", df.format(calendar.getTime()));

                break;
            }
        }

        return rs;
    }

    /**
     * 获取某日期的年份字符串
     * @param date
     * @return 字符串类型的年份
     */
    public static String getYearString(Date date) {
        return DateUtil.date(date, DEFAULT_YEAR_FORMAT);
    }

    /**
     * 获取某日期的年份数字
     * @param date
     * @return 数字类型的年份
     */
    public static int getYearInteger(Date date) {
        return Integer.parseInt(DateUtil.date(date, DEFAULT_YEAR_FORMAT));
    }

    /**
     * 获取某日期的月份字符串
     * @param date
     * @return
     */
    public static String getMonthString(Date date) {
        return DateUtil.date(date, DEFAULT_MONTH_FORMAT);
    }

    public static String getDayString(Date date) {
        return DateUtil.date(date, DEFAULT_Day_FORMAT);
    }


    /**
     * 获取某日期的月份数字
     * @param date
     * @return 数字类型的月份
     */
    public static int getMonthInteger(Date date) {
        return Integer.parseInt(DateUtil.date(date, DEFAULT_MONTH_FORMAT));
    }

    /**
     * 取得当前月的的最后一天
     * @param year
     * @param month
     * @return
     */
    public static Date getLastDayOfCurMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);// 年
        cal.set(Calendar.MONTH, month);// 月,因为Calendar里的月是从0开始,所以要减1
        cal.set(Calendar.DATE, 1);// 日,设为一号
        // cal.add(Calendar.MONTH, 1);// 月份加一,得到下个月的一号
        cal.add(Calendar.DATE, -1);// 下一个月减一为本月最后一天
        return cal.getTime();// 获得月末是几号
    }

    /**
     * 取得当前月的的第一天
     * @param year
     * @param month
     * @return
     */
    public static Date getFirstDayOfCurMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);// 年
        cal.set(Calendar.MONTH, month - 1);// 月,因为Calendar里的月是从0开始,所以要减1
        cal.set(Calendar.DATE, 1);// 日,设为一号
        // cal.add(Calendar.MONTH, 1);// 月份加一,得到下个月的一号
        cal.add(Calendar.DATE, 0);// 下一个月减一为本月最后一天
        return cal.getTime();// 获得月末是几号
    }

    /** */
    /**
     * 取得某天所在周的第一天
     * @param date
     * @return
     */
    public static Date getFirstDayOfWeek(Date date) {
        Calendar c = new GregorianCalendar();
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.setTime(date);
        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
        return c.getTime();
    }

    /** */
    /**
     * 取得某天所在周的最后一天
     * @param date
     * @return
     */
    public static Date getLastDayOfWeek(Date date) {
        Calendar c = new GregorianCalendar();
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.setTime(date);
        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6);
        return c.getTime();
    }

    /**
     * 验证日期是否有效,有效日期范围1900-1-1到2099-12-31.
     */
    public static boolean isValidDate(String ds) {
        if (StringUtils.isBlank(ds))
            return false;
        return pattern.matcher(ds).matches();
    }

    /**
     * 验证日期是否有效,有效日期范围1900-1-1到2099-12-31.
     */
    public static boolean isValidDate(Date d) {
        if (d == null)
            return false;
        return pattern.matcher(date(d, DEFAULT_DATE_FORMAT)).matches();
    }

    /**
     * 根据年月得到当月的天数
     *
     * @param date(格式:yyyy-MM)
     * @return
     */
    public static int getActualDays(String date) {
        Calendar rightNow = Calendar.getInstance();
        SimpleDateFormat simpleDate = new SimpleDateFormat(YEAR_MONTH_FORMAT); //如果写成年月日的形式的话,要写小d,如:"yyyy/MM/dd"
        try {
            rightNow.setTime(simpleDate.parse(date)); //要计算你想要的月份,改变这里即可
        } catch (ParseException e) {
            logger.error("解析日期失败!", e);
        }
        int days = rightNow.getActualMaximum(Calendar.DAY_OF_MONTH);
        return days;
    }

    /**
     * 根据年月得到当月的天数组成的年月日格式yyyyMMdd
     *
     * @param date(格式:yyyy-MM)
     * @return
     */
    public static String getActualDate(String date) {
        StringBuffer sb = new StringBuffer(date);
        int days = getActualDays(date);

        return sb.append(days).toString().replaceAll("/", "");
    }

    /**
     * 根据年月得到日期为第一天的日期格式yyyyMM01
     *
     * @param date(格式:yyyy-MM)
     * @return
     */
    public static String getFirstDate(String date) {
        StringBuffer sb = new StringBuffer(date);
        int days = getActualDays(date);

        return sb.append(days).toString().replaceAll("/", "");
    }

    /**
     * 比较2个日期的前后
     *
     * @param date1
     * @param date2
     * @return -1代表第一个日期小,1代表第一个日期大,0代表两个日期相等
     * @Description: 比较2个时间的前后
     */
    public static int compareDate(Date date1, Date date2) {
        Date dt1 = dateOnlyExt(date1);
        Date dt2 = dateOnlyExt(date2);
        if (dt1.getTime() > dt2.getTime()) {
            return 1;
        } else if (dt1.getTime() < dt2.getTime()) {
            return -1;
        } else {
            return 0;
        }

//      Calendar c1=Calendar.getInstance();
//      Calendar c2=Calendar.getInstance();
//      c1.setTime(dt1);
//      c2.setTime(dt2);
//      int result=c1.compareTo(c2);
//      if(result==0) //c1等于c2
//          return 0;
//      else if(result<0)//c1小于c2
//          return -1;
//      else    //c1大于c2
//          return 1;
    }

    /**
     * @param pattern
     * @return
     * @Description: 获取当前日期
     */
    public static String getCurrentDate(String pattern) {
        return date(new Date(), pattern);
    }

    /**
     * @return
     * @Description: 获取当前日期
     */
    public static String getCurrentDate() {
        return getCurrentDate(DEFAULT_DATE_FORMAT);
    }

    /**
     * @return
     * @Description: 获取当前时间
     */
    public static String getCurrentDateTime() {
        return getCurrentDate(DEFAULT_DATETIME_FORMAT);
    }


    /**
     * @param dateTime 格式为"yyyyMM"的字符串
     * @return foreYearMonth 返回前一个月的日期(格式"yyyyMM")
     * @Description: 获取某一日期的前一个月的日期(只取年月"yyyyMM")
     */
    public static String getForeYearMonth(String dateTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        String foreYearMonth = "";
        try {
            Date rtime = sdf.parse(dateTime);
            Calendar cal = Calendar.getInstance();
            cal.setTime(rtime);
            cal.add(Calendar.MONTH, -1);
            foreYearMonth = sdf.format(cal.getTime());
            ;
        } catch (ParseException e) {
            logger.error("日期计算异常!", e);
        }
        return foreYearMonth;
    }

    /**
     * @param year 某一年 ("yyyy")
     * @return foreYear 其前一年
     * @Description: 获取某一年的前一年("yyyy")
     * @date 2017年5月6日 下午5:07:18
     */
    public static String getForeYear(String year) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        String foreYear = "";
        try {
            Date rtime = sdf.parse(year);
            Calendar cal = Calendar.getInstance();
            cal.setTime(rtime);
            cal.add(Calendar.YEAR, -1);
            foreYear = sdf.format(cal.getTime());
        } catch (ParseException e) {
            logger.error("年份计算异常!", e);
        }
        return foreYear;
    }

    /**
     * @param dateTime 格式("yyyyMMdd")
     * @return
     * @Description: 判断某个日期是否是这个月的最后一天
     */
    public static boolean getIsTheMonthEnd(String dateTime) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date rtime = new Date();
        try {
            rtime = sdf.parse(dateTime);
        } catch (ParseException e) {
            logger.error("日期判断异常!", e);
        }

        Calendar cal = Calendar.getInstance();
        cal.setTime(rtime);
        int monthLastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);//获取当前月最后一天的数字,如20
        int dateInMonth = cal.get(Calendar.DAY_OF_MONTH);//获取指定日期的当前月数字,如20
        if (monthLastDay == dateInMonth) {
            return true;
        } else {
            return false;
        }

    }

    /**
     * @param date 年月  如:201704
     * @return 返回某月的最后一天的日期值 如:20
     * @Description: 获取某月的最后一天的日期值 如:20
     */
    public static int getTheMonthEndDay(String date) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        Date rtime = new Date();
        try {
            rtime = sdf.parse(date);
        } catch (ParseException e) {
            logger.error("日期格式化异常!", e);
        }

        Calendar cal = Calendar.getInstance();
        cal.setTime(rtime);
        int monthLastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);//获取当前月最后一天的数字,如20

        return monthLastDay;
    }

    /**
     * @param date 年月 如:201704
     * @param pre  前缀 如:2017
     * @param back 后缀 如:日
     * @return 返回该月自定义数组
     * @Description: 根据年月生成该月的自定义数组
     */
    public static List<Object> getTheMonthDayList(String date, String pre, String back) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        Date rtime = new Date();
        try {
            rtime = sdf.parse(date);
        } catch (ParseException e) {
            logger.error("日期格式化异常!", e);
        }

        Calendar cal = Calendar.getInstance();
        cal.setTime(rtime);
        int monthLastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);//获取当前月最后一天的数字,如20
        List<Object> dateList = new ArrayList<Object>();
        for (int i = 1; i <= monthLastDay; i++) {
            String j = "";
            if (i < 10) {
                j = "0" + i;
            } else {
                j = "" + i;
            }
            dateList.add(pre + j + back);
        }
        return dateList;
    }


    /**
     * @param bit  集合大小
     * @param pre  数据前缀
     * @param back 数据后缀
     * @return
     * @Description: 获取自定义大小和样式的数据集合
     */
    public static List<Object> getTheAutoList(int bit, String pre, String back) {

        List<Object> dateList = new ArrayList<Object>();
        for (int i = 1; i <= bit; i++) {
            String j = "";
            if (i < 10) {
                j = "0" + i;
            } else {
                j = "" + i;
            }
            dateList.add(pre + j + back);
        }
        return dateList;
    }

    /**
     * @param year
     * @return 返回日期数组 格式为:yyyyMMdd
     * @Description: 获取当年的日期数组(格式yyyy)
     */
    public static List<Object> getTheYearDaysList(int year) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Calendar calBegin = Calendar.getInstance();

        Date dBegin = getYearFirstDay(year);// 获取指定年份的第一天
        calBegin.setTime(dBegin);// 使用给定的 Date 设置此 Calendar 的时间

        Date dEnd = getYearLastDay(year);//获取指定年份的最后一天

        List<Object> dateList = new ArrayList<Object>();
        dateList.add(sdf.format(dBegin));
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())) {
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            dateList.add(sdf.format(calBegin.getTime()));
        }

        return dateList;

    }

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

    /**
     * @param year
     * @return
     * @Description: 获取某年最后一天日期
     */
    public static Date getYearLastDay(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        calendar.roll(Calendar.DAY_OF_YEAR, -1);
        Date currYearLast = calendar.getTime();

        return currYearLast;
    }

    /**
     * @Description: 获取Timestamp 时间对应格式化的时间字符串
     * @param  s s
     * @return
     * @throws ParseException
     */
    public static String getTimestampStr(Timestamp s) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATETIME_FORMAT);
        String dateStr="";

        try {
             dateStr=format.format(s);
        } catch (Exception e) {
            logger.error("Timestamp日期格式化错误",e);
        }
        return dateStr;
    }


    /**
     * @Description: 根据Timestamp时间获取对应格式的时间字符串 
     * @param s
     * @param sf 格式 如:M月d日 HH:mm 或 yyyy年M月
     * @return
     */
    public static String getFormatMonthDateTimeStr(Timestamp s, String sf) {
        SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_DATETIME_FORMAT);
        SimpleDateFormat sdfmdt = new SimpleDateFormat(sf);
        String returnString = null;
        try {
            String tsStr=getTimestampStr(s);
            Date datetime=sdf.parse(tsStr);
            //组装格式为:8月8日 08:20 或 2017年8月
            returnString=sdfmdt.format(datetime);
        } catch (Exception e) {
            logger.error("getFormatMonthDateTimeStr:日期格式化错误",e);
        }
        return returnString;
    }

    /**
     * 
     * @Description: 将时间字符串转为特定的格式
     * @param dateTime
     * @param formatPattern
     * @return
     */
    public static Date formatDateTime(String dateTime, String formatPattern) {
        try {
            if (StringUtils.isNotBlank(dateTime)
                    && StringUtils.isNotBlank(formatPattern)) {
                SimpleDateFormat format = new SimpleDateFormat(formatPattern);
                return format.parse(dateTime);
            }
        } catch (ParseException e) {
            logger.error("DateUtil::formatDateTime::字符串转日期对象异常", e);
        }

        return null;
    }

    /**
     * 获取格林尼日时间
     * @return
     */
    public static Date getDate1970(){
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(0);
        return c.getTime();
    }

}

猜你喜欢

转载自blog.csdn.net/qq_21955179/article/details/79381894
今日推荐