关于java:Java-时间工具类-总结

37次阅读

共计 29784 个字符,预计需要花费 75 分钟才能阅读完成。

Date 类

Date():空参数结构,会以以后操作系统的工夫结构一个 Date 对象。
long getTime():获取到从 1970 年开始,到这个 Date 对象示意的工夫,过了多少毫秒,返回工夫戳

public static void dateApi() {Date d1 = new Date();
    System.out.println(d1); //Mon Jul 19 20:42:57 CST 2021
    System.out.println(d1.getTime()); //1626698635074

}

Date 日期类型的大小比拟

办法一:java.util.Date 类实现了 Comparable 接口,能够间接调用 Date 的 compareTo()办法来比拟大小

String beginTime = "2018-07-28 14:42:32";
String endTime = "2018-07-29 12:26:32";
 
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
try {Date date1 = format.parse(beginTime);
    Date date2 = format.parse(endTime);
    
    int compareTo = date1.compareTo(date2);
    
    System.out.println(compareTo);
    
} catch (ParseException e) {e.printStackTrace();
}

compareTo()办法的返回值,date1 小于 date2 返回 -1,date1 大于 date2 返回 1,相等返回 0

办法二:通过 Date 自带的 before()或者 after()办法比拟

String beginTime = "2018-07-28 14:42:32";
String endTime = "2018-07-29 12:26:32";
 
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
try {Date date1 = format.parse(beginTime);
    Date date2 = format.parse(endTime);
    
    boolean before = date1.before(date2);
    
    System.out.println(before);
    
} catch (ParseException e) {e.printStackTrace();
}

before()或者 after()办法的返回值为 boolean 类型

办法三:通过调用 Date 的 getTime()办法获取到毫秒数来进行比拟

String beginTime = "2018-07-28 14:42:32";
String endTime = "2018-07-29 12:26:32";
 
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
try {Date date1 = format.parse(beginTime);
    Date date2 = format.parse(endTime);
    
    long beginMillisecond = date1.getTime();
    long endMillisecond = date2.getTime();
    
    System.out.println(beginMillisecond > endMillisecond);
    
} catch (ParseException e) {e.printStackTrace();
}

Calendar 类

Calendar 提供了很不便的不同日期格局的解决

public static void main(String[] args) {System.out.println("------------Calendar 无参结构 ------------");
    //Calendar 对象,不传参数,默认为以后日期
    Calendar calendar =new GregorianCalendar();
    // 获取以后年份
    System.out.println(calendar.get(Calendar.YEAR));
    // 获取以后月份 从 0 开始,0 代表一月,1 代表二月,以此类推
    System.out.println(calendar.get(Calendar.MONTH));
    // 获取以后日期 也能够应用 DAY_OF_MONTH
    System.out.println(calendar.get(Calendar.DATE));
    // 获取以后时 24 小时进制
    System.out.println(calendar.get(Calendar.HOUR_OF_DAY));
    // 获取以后分
    System.out.println(calendar.get(Calendar.MINUTE));
    // 获取以后秒
    System.out.println(calendar.get(Calendar.SECOND));

    // 获取明天是这个月的第几个星期
    System.out.println(calendar.get(Calendar.WEEK_OF_MONTH));
    // 获取明天是星期几  1 示意星期天,2 示意星期一,以此类推
    System.out.println(calendar.get(Calendar.DAY_OF_WEEK));


    System.out.println("------------Calendar 有参结构 ------------");
    /**
         * 有参结构 别离代表年月日时分秒,写法简单明了,很合乎咱们人类的思维
         * 留神月份的设置是从 0 开始的,这里设置的是月份是 6,理论是设置了 7 月份
         */
    calendar =new GregorianCalendar(2019, 6, 14, 16, 15,30);
    /**
         * 除了在构造方法间接设置之外,也能够通过 set 办法设置
         * 第一个参数示意设置的参数类型,第二个示意具体值
         */
    calendar.set(Calendar.YEAR, 2000);
    calendar.set(Calendar.MONTH, 0);
    calendar.set(Calendar.DATE, 20);
    //...


    System.out.println("------------Calendar 和 Date 转换 ------------");
    Date now = calendar.getTime();
    calendar.setTime(now);


    System.out.println("------------Calendar 日期计算以及判断 ------------");
    calendar = new GregorianCalendar();
    Calendar calendar2 = new GregorianCalendar();
    calendar2.set(Calendar.YEAR, 2800);
    // 是否在某个工夫 (calendar2) 之后
    System.out.println(calendar.after(calendar2));
    // 是否在某个工夫 (calendar2) 之前
    System.out.println(calendar.before(calendar2));
    // 减少多少年年,月日以及时分秒同理
    calendar.add(Calendar.YEAR, -10);

}

Time 类

java.time 包中的是类是不可变且线程平安的。
●Instant——它代表的是工夫戳
●LocalDate——不蕴含具体工夫的日期,比方 2014-01-14。它能够用来存储生日,周年纪念日,入职日期等。
●LocalTime——它代表的是不含日期的工夫
●LocalDateTime——它蕴含了日期及工夫,不过还是没有偏移信息或者说时区。
●ZonedDateTime——这是一个蕴含时区的残缺的日期工夫,偏移量是以 UTC/ 格林威治工夫为基准的。

/**
1.LocalDateTime 相较于 LocalDate、LocalTime,应用频率要高
2. 相似于 Calendar
*/


//now(): 获取以后的日期、工夫、日期 + 工夫
LocalDate localDate = LocalDate.now();  //2021-02-04
LocalTime localTime = LocalTime.now();  //10:11:34.741
LocalDateTime localDateTime = LocalDateTime.now();  //2021-02-04T10:11:34.768

//of(): 设置指定的年、月、日、时、分、秒。没有偏移量
LocalDateTime localDateTime1 = LocalDateTime.of(2020, 10, 6, 13, 23, 43);
System.out.println(localDateTime1);  //2020-10-06T13:23:43

//getXxx():获取相干的属性
System.out.println(localDateTime.getDayOfMonth()); //4 日期
System.out.println(localDateTime.getDayOfWeek());  //THURSDAY 星期
System.out.println(localDateTime.getMonth());       //FEBRUARY 月份    
System.out.println(localDateTime.getMonthValue()); //2 月份
System.out.println(localDateTime.getMinute());     //12 分


// 体现不可变性
//withXxx(): 设置相干的属性
LocalDate localDate1 = localDate.withDayOfMonth(22);
System.out.println(localDate);  //2021-02-04
System.out.println(localDate1); //2021-02-22


LocalDateTime localDateTime2 = localDateTime.withHour(4);
System.out.println(localDateTime);
System.out.println(localDateTime2);

// 不可变性
LocalDateTime localDateTime3 = localDateTime.plusMonths(3);
System.out.println(localDateTime);
System.out.println(localDateTime3);

LocalDateTime localDateTime4 = localDateTime.minusDays(6);
System.out.println(localDateTime);
System.out.println(localDateTime4);

java.sql.Timestamp:工夫戳,适配于 SQL 中的 TIMESTAMP 类型而呈现的,准确到纳秒级别。

DateFormat 类 与 SimpleDateFormat 类

DateFormat 类和 SimpleDateFormat 类来格式化日期
DateFormat 位于 text 包中,它是一个抽象类,不能被实例化
DateFormat 类是 SimpleDateFormat 类父类
SimpleDateFormat 是一个以与语言环境无关的形式来格式化和解析日期的具体类。它容许进行格式化(日期 -> 文本)、解析(文本 -> 日期)和规范化。

应用样例

// 工夫格式化
DateFormat tf1 = DateFormat.getTimeInstance(DateFormat.FULL, Locale.CHINA);
DateFormat tf2 = DateFormat.getTimeInstance(DateFormat.LONG, Locale.CHINA);
DateFormat tf3 = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.CHINA);
DateFormat tf4 = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.CHINA);
String t1 = tf1.format(new Date());
String t2 = tf2.format(new Date());
String t3 = tf3.format(new Date());
String t4 = tf4.format(new Date());

// 日期格式化
DateFormat df1 = DateFormat.getDateInstance(DateFormat.FULL, Locale.CHINA);
DateFormat df2 = DateFormat.getDateInstance(DateFormat.LONG, Locale.CHINA);
DateFormat df3 = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.CHINA);
DateFormat df4 = DateFormat.getDateInstance(DateFormat.SHORT, Locale.CHINA);
String d1 = df1.format(new Date());
String d2 = df2.format(new Date());
String d3 = df3.format(new Date());
String d4 = df4.format(new Date());

// 输入日期
System.err.println(d1 + "|eguid|" + t1);
System.err.println(d2 + "|eguid|" + t2);
System.err.println(d3 + "|eguid|" + t3);
System.err.println(d4 + "|eguid|" + t4);

后果
2018 年 10 月 15 日 |eguid| 星期一 上午 09 时 30 分 43 秒 CST
2018 年 10 月 15 日 |eguid| 上午 09 时 30 分 43 秒
2018-10-15 |eguid| 9:30:43
18-10-15 |eguid| 上午 9:30

import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @auother eguid
*/
public class DateTest {public static void main(String[] args) {SimpleDateFormat sdf = new SimpleDateFormat("yyyy 年 MM 月 dd 日  HH 点 mm 分 ss 秒");
        System.err.println(sdf.format(new Date())); // 格式化以后日期工夫
    }
}


2018 年 10 月 15 日 09 点 26 分 23 秒

DateFormatUtils 类

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package org.apache.commons.lang.time;

import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public class DateFormatUtils {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");
    public static final FastDateFormat ISO_TIME_NO_T_FORMAT = FastDateFormat.getInstance("HH:mm:ss");
    public static final FastDateFormat ISO_TIME_NO_T_TIME_ZONE_FORMAT = FastDateFormat.getInstance("HH:mm:ssZZ");
    public static final FastDateFormat SMTP_DATETIME_FORMAT;

    public DateFormatUtils() {}

    public static String formatUTC(long millis, String pattern) {return format((Date)(new Date(millis)), pattern, DateUtils.UTC_TIME_ZONE, (Locale)null);
    }

    public static String formatUTC(Date date, String pattern) {return format((Date)date, pattern, DateUtils.UTC_TIME_ZONE, (Locale)null);
    }

    public static String formatUTC(long millis, String pattern, Locale locale) {return format(new Date(millis), pattern, DateUtils.UTC_TIME_ZONE, locale);
    }

    public static String formatUTC(Date date, String pattern, Locale locale) {return format(date, pattern, DateUtils.UTC_TIME_ZONE, locale);
    }

    public static String format(long millis, String pattern) {return format((Date)(new Date(millis)), pattern, (TimeZone)null, (Locale)null);
    }

    public static String format(Date date, String pattern) {return format((Date)date, pattern, (TimeZone)null, (Locale)null);
    }

    public static String format(Calendar calendar, String pattern) {return format((Calendar)calendar, pattern, (TimeZone)null, (Locale)null);
    }

    public static String format(long millis, String pattern, TimeZone timeZone) {return format((Date)(new Date(millis)), pattern, timeZone, (Locale)null);
    }

    public static String format(Date date, String pattern, TimeZone timeZone) {return format((Date)date, pattern, timeZone, (Locale)null);
    }

    public static String format(Calendar calendar, String pattern, TimeZone timeZone) {return format((Calendar)calendar, pattern, timeZone, (Locale)null);
    }

    public static String format(long millis, String pattern, Locale locale) {return format((Date)(new Date(millis)), pattern, (TimeZone)null, locale);
    }

    public static String format(Date date, String pattern, Locale locale) {return format((Date)date, pattern, (TimeZone)null, locale);
    }

    public static String format(Calendar calendar, String pattern, Locale locale) {return format((Calendar)calendar, pattern, (TimeZone)null, locale);
    }

    public static String format(long millis, String pattern, TimeZone timeZone, Locale locale) {return format(new Date(millis), pattern, timeZone, locale);
    }

    public static String format(Date date, String pattern, TimeZone timeZone, Locale locale) {FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale);
        return df.format(date);
    }

    public static String format(Calendar calendar, String pattern, TimeZone timeZone, Locale locale) {FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale);
        return df.format(calendar);
    }

    static {SMTP_DATETIME_FORMAT = FastDateFormat.getInstance("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US);
    }
}

DateUtils 类

源码

package com.xinchacha.security.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName DateUtils
 * @Description TODO
 * @Author yiGeXinDong
 * @Date 2020/5/11 9:53
 * @Version 1.0
 **/
public class DateUtils   {
    public final static int FORMAT_DEFAULT = 0; // 默认格局

    /** 日时字符串格局:长格局(如:年份用 4 位示意)*/
    public final static int FORMAT_LONG = 1; // 长格局(如:年份用 4 位示意)/** 日时字符串格局:短格局(如:年份用 2 位示意)*/
    public final static int FORMAT_SHORT = 2; // 短格局(如:年份用 2 位示意)/** 默认日期字符串格局 "yyyy-MM-dd" */
    public final static String DATE_DEFAULT = "yyyy-MM-dd";
    /** 日期字符串格局 "yyyy" */
    private final static String DATE_YYYY="yyyy";
    /** 日期字符串格局 "mm" */
    private final static String DATE_MM="mm";
    /** 日期字符串格局 "dd" */
    private final static String DATE_DD="dd";
    /** 日期字符串格局 "yyyyMM" */
    public final static String DATE_YYYYMM = "yyyyMM";

    /** 日期字符串格局 "yyyyMMdd" */
    public final static String DATE_YYYYMMDD = "yyyyMMdd";

    /** 日期字符串格局 "yyyy-MM" */
    public final static String DATE_YYYY_MM = "yyyy-MM";

    /** 日期字符串格局 "yyyy-MM-dd" */
    public final static String DATE_YYYY_MM_DD = "yyyy-MM-dd";

    /** 默认日时字符串格局 "yyyy-MM-dd HH:mm:ss" */
    public final static String DATETIME_DEFAULT = "yyyy-MM-dd HH:mm:ss";

    /** 日时字符串格局 "yyyy-MM-dd HH:mm" */
    public final static String DATETIME_YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";

    /** 日时字符串格局 "yyyy-MM-dd HH:mm:ss" */
    public final static String DATETIME_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    /** 日时字符串格局 "yyyy-MM-dd HH:mm:ss.SSS" */
    public final static String DATETIME_YYYY_MM_DD_HH_MM_SS_SSS = "yyyy-MM-dd HH:mm:ss.SSS";

    /** 默认工夫字符串格局 "HH:mm:ss" */
    public final static String TIME_DEFAULT = "HH:mm:ss";

    /** 默认工夫字符串格局 "HH:mm" */
    public final static String TIME_HH_MM = "HH:mm";

    /** 默认工夫字符串格局 "HH:mm:ss" */
    public final static String TIME_HH_MM_SS = "HH:mm:ss";
    public static final long YEAR_NUMBER=365;
    /** 分 */
    public static final long MINUTE_TTL = 60 * 1000l;
    /** 时 */
    public static final long HOURS_TTL = 60 * 60 * 1000l;
    /** 半天 */
    public static final long HALF_DAY_TTL = 12 * 60 * 60 * 1000l;
    /** 天 */
    public static final long DAY_TTL = 24 * 60 * 60 * 1000l;
    /** 月 */
    public static final long MONTH_TTL = 30 * 24 * 60 * 60 * 1000l;



    /**
     * TODO 计算两个工夫差值
     * @param startDate,endDate
     * @Author XuWenXiao
     * @return int(两个工夫相差的天数)
     * @throws ParseException
     */
    public static int daysBetween(Date startDate, Date endDate) throws ParseException {Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        long sTime = calendar.getTimeInMillis();
        calendar.setTime(endDate);
        long endTime = calendar.getTimeInMillis();
        long between_days=(endTime-sTime)/DAY_TTL;
        return Integer.parseInt(String.valueOf(between_days));
    }
    /**
     * TODO 获取以后零碎工夫
     * @Author XuWenXiao
     * @return Date
     */
    public static Date getNewDate(){SimpleDateFormat df = new SimpleDateFormat(DATETIME_YYYY_MM_DD_HH_MM_SS);// 设置日期格局
        Date newDate=null;
        try {newDate=df.parse(df.format(new Date()));
        } catch (ParseException e) {e.printStackTrace();
        }
        return newDate;
    }
    /**
     * 失去日期字符串 默认格局(yyyy-MM-dd)pattern 能够为:"yyyy-MM-dd" "HH:mm:ss" "E"
     */
    public static String formatDate(Date date, Object... pattern) {
        String formatDate = null;
        if (pattern != null && pattern.length > 0) {formatDate = DateFormatUtils.format(date, pattern[0].toString());
        } else {formatDate = DateFormatUtils.format(date, DATE_YYYY_MM_DD);
        }
        return formatDate;
    }
    /**
     * 失去以后年份字符串 格局(yyyy)*/
    public static String getYear() {return formatDate(new Date(), DATE_YYYY);
    }
    /**
     * 失去以后月份字符串 格局(MM)*/
    public static String getMonth() {return formatDate(new Date(), DATE_MM);
    }
    /**
     * 失去当天字符串 格局(dd)*/
    public static String getDay() {return formatDate(new Date(), DATE_DD);
    }
    /**
     * 获取以后工夫的字符串模式(例如;"201806291135")* @return 年月日时分
     */
    public static String getDateToString(){Calendar c = Calendar.getInstance();
        return getYear()+getMonth()+getDay()+c.get(Calendar.HOUR_OF_DAY)+c.get(Calendar.MINUTE);
    }
    /**
     * 获取过来的年数
     * @param date
     * @return
     */
    public static Long pastYear(Date date) {return date==null?null:pastDays(date)/YEAR_NUMBER;
    }

    /**
     * 获取过来的天数
     * @param date
     * @return
     */
    public static long pastDays(Date date) {long t = new Date().getTime()-date.getTime();
        return t/DAY_TTL;
    }

    /**
     * 获取过来的小时
     * @param date
     * @return
     */
    public static long pastHour(Date date) {long t = new Date().getTime()-date.getTime();
        return t/HOURS_TTL;
    }

    /**
     * 获取过来的分钟
     * @param date
     * @return
     */
    public static long pastMinutes(Date date) {long t = new Date().getTime()-date.getTime();
        return t/MINUTE_TTL;
    }
    /**
     * 获取两个日期之间的天数
     *
     * @param before
     * @param after
     * @return
     */
    public static double getDistanceOfTwoDate(Date before, Date after) {long beforeTime = before.getTime();
        long afterTime = after.getTime();
        return (afterTime - beforeTime) /DAY_TTL;
    }
    /**
     * 依据身份证计算出身日期
     *
     */
    /**
     * 通过身份证号码获取出生日期、性别、年齡
     * @param certificateNo
     * @return 返回的出生日期格局:1990-01-01   性别格局:2- 女,1- 男
     */
    public static Map<String, String> getBirAgeSex(String certificateNo) {System.out.println(certificateNo);
        String birthday = "";
        String age = "";
        String sexCode = "";
        int year = Calendar.getInstance().get(Calendar.YEAR);
        char[] number = certificateNo.toCharArray();
        boolean flag = true;
        if (number.length == 15) {for (int x = 0; x < number.length; x++) {if (!flag) return new HashMap<String, String>();
                flag = Character.isDigit(number[x]);
            }
        } else if (number.length == 18) {for (int x = 0; x < number.length - 1; x++) {if (!flag) return new HashMap<String, String>();
                flag = Character.isDigit(number[x]);
            }
        }
        if (flag && certificateNo.length() == 15) {birthday = "19" + certificateNo.substring(6, 8) + "-"
                    + certificateNo.substring(8, 10) + "-"
                    + certificateNo.substring(10, 12);
            sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 3, certificateNo.length())) % 2 == 0 ? "2" : "1";
            age = (year - Integer.parseInt("19" + certificateNo.substring(6, 8))) + "";
        } else {birthday = certificateNo.substring(6, 10) + "-"
                    + certificateNo.substring(10, 12) + "-"
                    + certificateNo.substring(12, 14);
            sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 4, certificateNo.length() - 1)) % 2 == 0 ? "2" : "1";
            age = (year - Integer.parseInt(certificateNo.substring(6, 10))) + "";
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("birthday", birthday);
        map.put("age", age);
        map.put("sexCode", sexCode);
        return map;
    }
    /**
     * 依据身份证的号码算出以后身份证持有者的年龄 18 位身份证
     * @author 黄涛
     * @return
     * @throws Exception
     */
    public static int getCarAge(String birthday){String year = birthday.substring(0, 4);// 失去年份
        String yue = birthday.substring(4, 6);// 失去月份
        //String day = birthday.substring(6, 8);//
        Date date = new Date();// 失去以后的零碎工夫
        SimpleDateFormat format = new SimpleDateFormat(DATE_YYYY_MM_DD);
        String fYear = format.format(date).substring(0, 4);// 以后年份
        String fYue = format.format(date).substring(5, 7);// 月份
        // String fday=format.format(date).substring(8,10);
        int age = 0;
        if (Integer.parseInt(yue) <= Integer.parseInt(fYue)) { // 以后月份大于用户出身的月份示意已过生
            age = Integer.parseInt(fYear) - Integer.parseInt(year) + 1;
        } else {// 以后用户还没过生
            age = Integer.parseInt(fYear) - Integer.parseInt(year);
        }
        return age;
    }
    /**
     *
     * 依据身份证获取性别
     */
    public static String getCarSex(String CardCode){
        String sex;
        if (Integer.parseInt(CardCode.substring(16).substring(0, 1)) % 2 == 0) {// 判断性别
            sex = "2";
        } else {sex = "1";}
        return sex;
    }



    /**
     * 依据传入的日历型日期,计算出执行的工夫值(准确版)* @param beginTime
     * @param endTime
     * @return
     */
    public static String countExecTimeToString_exact(Calendar beginTime,Calendar endTime)
    {// 计算两个日期类型之间的差值(单位:毫秒)Long timeDispersion = endTime.getTimeInMillis() - beginTime.getTimeInMillis();
        String tmpMsg = "耗时:";// 拼写输入的字符串
        int timeNum = 0;// 记录时间的数值(几小时、几分、几秒)if(timeDispersion >= (HOURS_TTL))// 判断是否足够一小时
        {// 若足够则计算有几小时
            timeNum = (int) (timeDispersion/HOURS_TTL);
            tmpMsg += timeNum + "时";// 拼写输入几小时
            timeDispersion = timeDispersion - (timeNum*HOURS_TTL);// 减去小时数(这样剩下的就是分钟数了)}
        if(timeDispersion >= (MINUTE_TTL))// 判断是否足够一分钟
        {// 若足够则计算有几分钟
            timeNum = (int) (timeDispersion/MINUTE_TTL);
            tmpMsg += timeNum + "分";// 拼写输入几分钟
            timeDispersion = timeDispersion - (timeNum*MINUTE_TTL);// 减去分钟数(这样就剩下秒数了)}
        if(timeDispersion >= 1000)// 判断是否足够一秒
        {// 若足够则计算几秒
            timeNum = (int) (timeDispersion/1000);
            tmpMsg +=  timeNum + "秒";// 拼写输入秒数
            timeDispersion = timeDispersion - timeNum*1000;// 减去秒数(这样就剩下毫秒数了)}
        tmpMsg += timeDispersion + "毫秒";// 拼写输入毫秒数
        return tmpMsg;

    }// 重载办法,返回 Long 类型(毫秒)public static Long countExecTimeToLong_exact(Calendar beginTime,Calendar endTime)
    {// 间接返回毫秒数
        return (endTime.getTimeInMillis() - beginTime.getTimeInMillis());
    }
    /**
     * 依据传入的 long 类型日期,计算出执行的工夫值(准确版)* @param beginTime
     * @param endTime
     * @return
     */
    public static String countExecTimeToString_exact(Long beginTime,Long endTime)
    {// 计算两个日期类型之间的差值(单位:毫秒)Long timeDispersion = endTime - beginTime;
        String tmpMsg = "耗时:";// 拼写输入的字符串
        int timeNum = 0;// 记录时间的数值(几小时、几分、几秒)if(timeDispersion >= (HOURS_TTL))// 判断是否足够一小时
        {// 若足够则计算有几小时
            timeNum = (int) (timeDispersion/(HOURS_TTL));
            tmpMsg += timeNum + "时";// 拼写输入几小时
            timeDispersion = timeDispersion - (timeNum*HOURS_TTL);// 减去小时数(这样剩下的就是分钟数了)}
        if(timeDispersion >= (MINUTE_TTL))// 判断是否足够一分钟
        {// 若足够则计算有几分钟
            timeNum = (int) (timeDispersion/(MINUTE_TTL));
            tmpMsg += timeNum + "分";// 拼写输入几分钟
            timeDispersion = timeDispersion - (timeNum*MINUTE_TTL);// 减去分钟数(这样就剩下秒数了)}
        if(timeDispersion >= 1000)// 判断是否足够一秒
        {// 若足够则计算几秒
            timeNum = (int) (timeDispersion/1000);
            tmpMsg +=  timeNum + "秒";// 拼写输入秒数
            timeDispersion = timeDispersion - timeNum*1000;// 减去秒数(这样就剩下毫秒数了)}
        tmpMsg += timeDispersion + "毫秒";// 拼写输入毫秒数
        return tmpMsg;

    }
    /**
     * 获取指定年度全副月份汇合 <br>
     * 格局为 yyyy-MM
     * @author 王鹏
     * @version 2019 年 11 月 16 日 下午 4:52:55
     * @param year 年度
     * @return
     */
    public static List<String> getYearMonthByYear(String year) {List<String> monthList =new ArrayList<>();
        for (int i = 1; i <= 12; i++) {monthList.add(year+"-"+(i<10?"0":"")+i);
        }
        return monthList;
    }

    /**
     * 获取下个月
     * dateStr 日期
     * format 格局:yyyy-MM 或 yyyyMM
     * @return
     */
    public static String getPreMonth(String dateStr,String format) {
        String preMonth = "";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date;
        try {date = sdf.parse(dateStr);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(calendar.MONTH, 1);
            sdf.format(calendar.getTime());

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();}
        return preMonth;
    }
    /**
     * 获取下个月
     * dateStr 日期
     * format 格局:yyyy-MM 或 yyyyMM
     * @return
     */
    public static String getPreMonthFormat(String dateStr,String format) {
        String preMonth = "";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date;
        try {date = sdf.parse(dateStr);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(calendar.MONTH, 1);
            preMonth= sdf.format(calendar.getTime());

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();}
        return preMonth;
    }
    /**
     * 日期比拟
     * date1 比 date2 大 true
     */
    public static boolean dateSize(String aDate,String bDate,SimpleDateFormat format) {
        boolean str = false;
        try {if(StringUtils.isNotBlank(aDate)&&StringUtils.isNotBlank(bDate)) {Date date1 = format.parse(aDate);
                Date date2 = format.parse(bDate);
                str = date1.after(date2);
            }
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();}
        return str;
    }

}



自定义 DateUtil 类

package com.jd.survey.common.utils;

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

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DateUtil {private static final Logger log = LoggerFactory.getLogger(DateUtil.class);
    private static final String default_format = "yyyy-MM-dd HH:mm:ss";
    private static final String format_yyyy = "yyyy";
    private static final String format_yyyyMM = "yyyy-MM";
    private static final String format_yyyyMMdd = "yyyy-MM-dd";
    private static final String format_yyyyMMddHH = "yyyy-MM-dd HH";
    private static final String format_yyyyMMddHHmm = "yyyy-MM-dd HH:mm";
    private static final String format_yyyyMMddHHmmss = "yyyy-MM-dd HH:mm:ss";
    public static final int MONDAY = 1;
    public static final int TUESDAY = 2;
    public static final int WEDNESDAY = 3;
    public static final int THURSDAY = 4;
    public static final int FRIDAY = 5;
    public static final int SATURDAY = 6;
    public static final int SUNDAY = 7;
    public static final int JANUARY = 1;
    public static final int FEBRUARY = 2;
    public static final int MARCH = 3;
    public static final int APRIL = 4;
    public static final int MAY = 5;
    public static final int JUNE = 6;
    public static final int JULY = 7;
    public static final int AUGUST = 8;
    public static final int SEPTEMBER = 9;
    public static final int OCTOBER = 10;
    public static final int NOVEMBER = 11;
    public static final int DECEMBER = 12;
    
    public static final Date parseDate(String strDate, String format) {
        SimpleDateFormat df = null;
        Date date = null;
        df = new SimpleDateFormat(format);

        try {date = df.parse(strDate);
        } catch (ParseException e) {}

        return (date);
    }

    public static Date now() {return new Date();
    }

    public static int getYear(Date datetime) {Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetime);
        return calendar.get(1);
    }

    public static int getDayOfMonth(Date datetime) {Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetime);
        return calendar.get(5);
    }

    public static int getMonthOfYear(Date datetime) {Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetime);
        return calendar.get(2) + 1;
    }

    public static int getDayOfWeek(Date datetime) {Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetime);
        calendar.setFirstDayOfWeek(2);
        int day = calendar.get(7) - 1;
        if (day == 0) {day = 7;}
        return day;
    }

    public static Date getTodayEndTime(){Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY,23);
        calendar.set(Calendar.MINUTE,59);
        calendar.set(Calendar.SECOND,59);
        return calendar.getTime();}

    public static int getDayOfYear(Date datetime) {Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetime);
        return calendar.get(6);
    }

    public static int getHourField(Date datetime) {Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetime);
        return calendar.get(11);
    }

    public static int getMinuteField(Date datetime) {Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetime);
        return calendar.get(12);
    }

    public static int getSecondField(Date datetime) {Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetime);
        return calendar.get(13);
    }

    public static int getMillisecondField(Date datetime) {Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetime);
        return calendar.get(14);
    }

    public static long getDays(Date datetime) {return datetime.getTime() / 86400000L;
    }

    public static long getHours(Date datetime) {return datetime.getTime() / 3600000L;
    }

    public static long getMinutes(Date datetime) {return datetime.getTime() / 60000L;
    }

    public static long getSeconds(Date datetime) {return datetime.getTime() / 1000L;
    }

    public static long getMilliseconds(Date datetime) {return datetime.getTime();
    }

    public static int getWeekOfMonth(Date datetime) {Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetime);
        calendar.setFirstDayOfWeek(2);
        return calendar.get(4);
    }

    public static int getWeekOfYear(Date datetime) {Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetime);
        calendar.setFirstDayOfWeek(2);
        return calendar.get(3);
    }

    public static int getMaxDateOfMonth(Date datetime) {Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetime);
        return calendar.getActualMaximum(5);
    }

    public static int getMaxDateOfYear(Date datetime) {Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetime);
        return calendar.getActualMaximum(6);
    }

    public static int getMaxWeekOfMonth(Date datetime) {Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetime);
        calendar.setFirstDayOfWeek(2);
        return calendar.getActualMaximum(4);
    }

    public static int getMaxWeekOfYear(Date datetime) {Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetime);
        calendar.setFirstDayOfWeek(2);
        return calendar.getActualMaximum(3);
    }

    public static Date toDatetime(String datetimeString, String format) {
        Date result = null;
        try {SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
            result = simpleDateFormat.parse(datetimeString);
        } catch (Exception e) {log.error("Fail to parse datetime.", e);
        }
        return result;
    }

    public static String toString(Date datetime) {return toString(datetime, null);
    }

    public static String toString(Date datetime, String format) {
        String result = null;
        SimpleDateFormat simpleDateFormat = null;
        try {if (StringUtils.isNoneBlank(new CharSequence[] {format})) {simpleDateFormat = new SimpleDateFormat(format);
            } else {simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            }
            result = simpleDateFormat.format(datetime);
        } catch (Exception e) {log.error("Fail to parse datetime.", e);
        }
        return result;
    }

    public static int diffYears(Date datetime1, Date datetime2) {Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetime1);
        int month1 = calendar.get(1);
        calendar.setTime(datetime2);
        int month2 = calendar.get(1);
        return month1 - month2;
    }

    public static int diffMonths(Date datetime1, Date datetime2) {Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetime1);
        int month1 = calendar.get(2);
        calendar.setTime(datetime2);
        int month2 = calendar.get(2);
        return month1 - month2;
    }

    public static long diffDays(Date datetime1, Date datetime2) {return (datetime1.getTime() - datetime2.getTime()) / 86400000L;
    }

    public static long diffDaysByCalendar(Date datetime1, Date datetime2)
            throws Exception {
        try {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            return diffDays(sdf.parse(sdf.format(datetime1)),
                    sdf.parse(sdf.format(datetime2)));
        } catch (Exception e) {throw e;}
    }

    public static long diffHours(Date datetime1, Date datetime2) {return (datetime1.getTime() - datetime2.getTime()) / 3600000L;
    }

    public static long diffMiniutes(Date datetime1, Date datetime2) {return (datetime1.getTime() - datetime2.getTime()) / 60000L;
    }

    public static long diffSeconds(Date datetime1, Date datetime2) {return (datetime1.getTime() - datetime2.getTime()) / 1000L;
    }

    public static Date add(Date datetime1, Date datetime2) {Calendar calendar = Calendar.getInstance();
        Date date = new Date(datetime1.getTime() + datetime2.getTime());
        return date;
    }

    public static Date minus(Date datetime1, Date datetime2) {Calendar calendar = Calendar.getInstance();
        Date date = new Date(datetime1.getTime() - datetime2.getTime());
        return date;
    }

    public static boolean isBefore(Date datetime1, Date datetime2) {return datetime2.getTime() - datetime1.getTime() > 0L;}

    public static boolean isBeforeOrEqual(Date datetime1, Date datetime2) {return datetime2.getTime() - datetime1.getTime() >= 0L;}

    public static boolean isEqual(Date datetime1, Date datetime2) {return datetime2.getTime() == datetime1.getTime();}

    public static boolean isAfter(Date datetime1, Date datetime2) {return datetime2.getTime() - datetime1.getTime() < 0L;}

    public static boolean isAfterOrEqual(Date datetime1, Date datetime2) {return datetime2.getTime() - datetime1.getTime() <= 0L;}

    public static Date addMilliseconds(Date datetime, int milliseconds) {Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetime);
        calendar.roll(14, milliseconds);
        return calendar.getTime();}

    public static Date addSeconds(Date datetime, int seconds) {Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetime);
        calendar.roll(13, seconds);
        return calendar.getTime();}

    public static Date addMinutes(Date datetime, int minutes) {Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetime);
        calendar.roll(12, minutes);
        return calendar.getTime();}

    public static Date addHours(Date datetime, int hours) {Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetime);
        calendar.roll(10, hours);
        return calendar.getTime();}

    public static Date addDays(Date datetime, int days) {Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetime);
        calendar.roll(5, days);
        return calendar.getTime();}

    public static Date addMonths(Date datetime, int months) {Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetime);
        calendar.roll(2, months);
        return calendar.getTime();}

    public static boolean isSameSecond(Date datetime1, Date datetime2) {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(datetime1).equals(sdf.format(datetime2));
    }

    public static boolean isSameMinute(Date datetime1, Date datetime2) {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return sdf.format(datetime1).equals(sdf.format(datetime2));
    }

    public static boolean isSameHour(Date datetime1, Date datetime2) {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH");
        return sdf.format(datetime1).equals(sdf.format(datetime2));
    }

    public static boolean isSameDay(Date datetime1, Date datetime2) {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(datetime1).equals(sdf.format(datetime2));
    }

    public static boolean isSameMonth(Date datetime1, Date datetime2) {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        return sdf.format(datetime1).equals(sdf.format(datetime2));
    }

    public static boolean isSameYear(Date datetime1, Date datetime2) {SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        return sdf.format(datetime1).equals(sdf.format(datetime2));
    }

    public static boolean isSameWeek(Date datetime1, Date datetime2) {
        boolean result = false;
        int year1 = getYear(datetime1);
        int year2 = getYear(datetime2);
        int month1 = getMonthOfYear(datetime1);
        int month2 = getMonthOfYear(datetime2);
        int dayOfWeek1 = getDayOfWeek(datetime1);
        int dayOfWeek2 = getDayOfWeek(datetime2);
        long diffDays = diffDays(datetime1, datetime2);
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(2);
        if (Math.abs(diffDays) < calendar.getMaximum(7)) {if (year1 == year2) {if (getWeekOfYear(datetime1) == getWeekOfYear(datetime2)) {result = true;}
            } else if ((year1 - year2 == 1) && (month1 == 1) && (month2 == 12)) {calendar.set(year1, 0, 1);
                int dayOfWeek = getDayOfWeek(calendar.getTime());
                if ((dayOfWeek2 < dayOfWeek) && (dayOfWeek <= dayOfWeek1)) {result = true;}
            } else if ((year2 - year1 == 1) && (month1 == 12) && (month2 == 1)) {calendar.set(year2, 0, 1);
                int dayOfWeek = getDayOfWeek(calendar.getTime());
                if ((dayOfWeek1 < dayOfWeek) && (dayOfWeek <= dayOfWeek2)) {result = true;}
            }
        }
        return result;
    }
}

参考资料

Java 中罕用的 Date 类型
https://blog.csdn.net/qiuwenjie123/article/details/79846621
Calendar 类简介
https://blog.csdn.net/qq_42815754/article/details/95896544
java 中 time 的工夫类
https://blog.csdn.net/ppppppushcar/article/details/113704597
Java 日期格式化:DateFormat 类和 SimpleDateFormat 类详解
https://blog.csdn.net/eguid/article/details/116054105

正文完
 0