java8 对LocalDate、localDateTime的操作

2022年11月20日07:57:15

 最近项目在做一些报表的统计,对时间的操作比较多,写个工具类记录一下

public class LocalDateUtils {
    public static final String FORMATTER_YYYYMMDDHHMMSS = "yyyy-MM-dd HH:mm:ss";
    public static final String FORMATTER_YYYYMMDDHHMM = "yyyy-MM-dd HH:mm";
    public static final String FORMATTER_YYYYMMDD = "yyyy-MM-dd";

    /**
     * 将Date类型转化为指定格式字符串
     * @param date
     * @param format
     * @return
     */
    public static String getStringByDate(Date date, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }

    /**
     * 将指定格式的字符串转化为Date
     * @param dateStr
     * @param format
     * @return
     */
    public static Date getDateByString(String dateStr, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取当前Date并转化为指定格式字符串
     * @param format
     * @return
     */
    public static String getCurrentDate(String format) {
        return getStringByDate(new Date(), format);
    }

    /**
     * 将Date转化为LocalDateTime
     * @param date
     * @return
     */
    public static LocalDateTime getLocalDateTime(Date date) {
        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    }

    /**
     * 将LocalDateTime转化为Date
     * @param localDateTime
     * @return
     */
    public static Date getDataByLocalDateTime(LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * 比较两个LocalDate的时间大小
     * @param localDate
     * @return 比较当前对象和other对象在时间上的大小,返回值如果为正,则当前对象时间较晚
     */
    public static int getLocalDateTime(LocalDate localDate) {
        return LocalDate.now().compareTo(localDate);
    }

    /**
     * 比较两个Date的时间大小
     * @param date
     * @param date2
     * @return
     */
    public static boolean getLocalDateTime(Date date, Date date2) {
        if (date.compareTo(date2) == 1) {
            return true;
        }
        return false;
    }

    /**
     * 将LocalDateTime转化为指定格式字符串
     * @param localDateTime
     * @param format
     * @return
     */
    public static String getStringByLocalDateTime(LocalDateTime localDateTime, String format) {
        return localDateTime.format(DateTimeFormatter.ofPattern(format));
    }

    /**
     * 将指定格式String类型日期转化为LocalDateTime
     * @param format
     * @param localDateTime
     * @return
     */
    public static LocalDateTime getLocalDateTimeByString(String format,String localDateTime) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
        return LocalDateTime.parse(localDateTime, df);
    }

    /**
     * 获取指定LocalDateTime的秒数
     * @param localDateTime
     * @return
     */
    public static Long getSecondByLocalDateTime(LocalDateTime localDateTime) {
        return localDateTime.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();
    }

    /**
     * 获取指定LocalDateTime的毫秒数
     * @param localDateTime
     * @return
     */
    public static Long getMillSecondByLocalDateTime(LocalDateTime localDateTime) {
        return localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }

    /**
     * 将LocalDateTime转化为默认yy-mm-dd hh:mm:ss格式字符串
     * @param localDateTime
     * @return
     */
    public static String getDefaultStringByLocalDateTime(LocalDateTime localDateTime,String format) {
        return getStringByLocalDateTime(localDateTime, format);
    }

    /**
     * 获取当前LocalDateTime并转化为指定格式字符串
     * @param format
     * @return
     */
    public static String getCurrentLocalDateTime(String format) {
        return getStringByLocalDateTime(LocalDateTime.now(), format);
    }

    /**
     * 获取一天的开始时间获取一天的开始时间
     * @param localDateTime
     * @return
     */
    public static String getStartTime(LocalDateTime localDateTime,String format) {
        return getDefaultStringByLocalDateTime(localDateTime.with(LocalTime.MIN),format);
    }

    /**
     * 获取当天的开始时间
     * @return
     */
    public static String getStartTime(String format) {
        return getDefaultStringByLocalDateTime(LocalDateTime.now(),format);
    }

    /**
     * 获取一天的结束时间
     * @param localDateTime
     * @return
     */
    public static String getEndTime(LocalDateTime localDateTime,String format) {
        return getDefaultStringByLocalDateTime(localDateTime.with(LocalTime.MAX),format);
    }

    /**
     * 获取当天的结束时间
     * @return
     */
    public static String getEndTime(String format) {
        return getDefaultStringByLocalDateTime(LocalDateTime.now(),format);
    }

    /**
     * 比较两个LocalDateTime的时间大小
     * @param localDateTime1
     * @param localDateTime2
     * @return
     */
    public static boolean getCompareLocalDateTime(LocalDateTime localDateTime1, LocalDateTime localDateTime2) {
        if (localDateTime1.isBefore(localDateTime2)) {
            return true;
        }
        return false;
    }

    /**
     * 计算两个指定格式String日期字符串的时间差(精确到毫秒)
     * @param format
     * @param time1
     * @param time2
     * @return
     */
    public static Long getCompareSecondLocalDateTime(String format ,String time1, String time2) {
        System.out.println("接收到的参数为:"+format+","+time1+","+time2);
        LocalDateTime localDateTime1 =getLocalDateTimeByString(format,time1);
        LocalDateTime localDateTime2 =getLocalDateTimeByString(format,time2);
        if(getMillSecondByLocalDateTime(localDateTime1)>getMillSecondByLocalDateTime(localDateTime2)) {
            return getMillSecondByLocalDateTime(localDateTime1)-getMillSecondByLocalDateTime(localDateTime2);
        }
        return getMillSecondByLocalDateTime(localDateTime2)-getMillSecondByLocalDateTime(localDateTime1);
    }

    /**
     * 获取两个LocalDateTime的天数差
     * @param localDateTime1
     * @param localDateTime2
     * @return
     */
    public static Long getCompareDayLocalDateTime(LocalDateTime localDateTime1, LocalDateTime localDateTime2) {
        if (getCompareLocalDateTime(localDateTime1, localDateTime2)) {
            Duration duration = Duration.between(localDateTime1, localDateTime2);
            return duration.toDays();
        } else {
            Duration duration = Duration.between(localDateTime2, localDateTime1);
            return duration.toDays();
        }
    }

    /**
     * 获取两个LocalDateTime的小时差
     * @param localDateTime1
     * @param localDateTime2
     * @return
     */
    public static Long getCompareYearLocalDateTime(LocalDateTime localDateTime1, LocalDateTime localDateTime2) {
        if (getCompareLocalDateTime(localDateTime1, localDateTime2)) {
            Duration duration = Duration.between(localDateTime1, localDateTime2);
            return duration.toHours();
        } else {
            Duration duration = Duration.between(localDateTime2, localDateTime1);
            return duration.toHours();
        }
    }

    /**
     * 判断两个字符串时间相隔的天数,并遍历输出这些字符串时间
     *
     * @param stime yyyy-MM-dd
     * @param etime yyyy-MM-dd
     * @return
     */
    public static List<String> getBetweenDays(String stime, String etime) {
        List<String>      dateList = new ArrayList<>();
        DateTimeFormatter df       = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate         sDate    = LocalDate.parse(stime);
        LocalDate         eDate    = LocalDate.parse(etime);
        //两个日期相差的天数
        long day = eDate.toEpochDay() - sDate.toEpochDay();
        System.out.println(day);
        for (int i = 0; i <= day; i++) {
            dateList.add(df.format(eDate.minusDays(i)));
        }
        return dateList;
    }

/**
     * 获取两个日期之间的所有月份 (年月)
     *
     * @param startTime
     * @param endTime
     * @return:YYYY-MM
     */
    public static List<String> getMonthBetweenDate(String startTime, String endTime){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        // 声明保存日期集合
        List<String> list = new ArrayList<String>();
        try {
            // 转化成日期类型
            Date startDate = sdf.parse(startTime);
            Date endDate = sdf.parse(endTime);
 
            //用Calendar 进行日期比较判断
            Calendar calendar = Calendar.getInstance();
            while (startDate.getTime()<=endDate.getTime()){
                // 把日期添加到集合
                list.add(sdf.format(startDate));
                // 设置日期
                calendar.setTime(startDate);
                //把日期增加一天
                calendar.add(Calendar.MONTH, 1);
                // 获取增加后的日期
                startDate=calendar.getTime();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return list;
    }


 /**
     * 获取两个时间段的时间段值
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param typeEnum 时间类型枚举
     * @return
     */
    protected static List<String> getTimePeriodFromTwoTime(Long startTime, Long endTime, TimeTypeEnum typeEnum) {
        LocalDate start = Instant.ofEpochMilli(startTime).atZone(ZoneOffset.ofHours(8)).toLocalDate();
        LocalDate end = Instant.ofEpochMilli(endTime).atZone(ZoneOffset.ofHours(8)).toLocalDate();

        List<String> result = new ArrayList<>();

        // 年
        if (typeEnum.getType().equals(TimeTypeEnum.YEAR.getType())) {
            Year startyear = Year.from(start);
            Year endYear = Year.from(end);
            // 包含最后一个时间
            for (long i = 0; i <= ChronoUnit.YEARS.between(startyear, endYear); i++) {
                result.add(startyear.plusYears(i).toString());
            }
        }
        // 月
        else if (TimeTypeEnum.MONTH.getType().equals(typeEnum.getType())) {
            YearMonth from = YearMonth.from(start);
            YearMonth to = YearMonth.from(end);
            for (long i = 0; i <= ChronoUnit.MONTHS.between(from, to); i++) {
                result.add(from.plusMonths(i).toString());
            }
        }
        // 日
        else {
            for (long i = 0; i <= ChronoUnit.DAYS.between(start, end); i++) {
                result.add(start.plus(i, ChronoUnit.DAYS).toString());
            }
        }
        return result;
    }


    /**
     * 获取当前时间本周开始日期
     */
    public static String getWeekStart() {
        LocalDateTime inputDate = LocalDateTime.now();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        TemporalAdjuster FIRST_OF_WEEK =
                TemporalAdjusters.ofDateAdjuster(localDate -> localDate.minusDays(localDate.getDayOfWeek().getValue()- DayOfWeek.MONDAY.getValue()));
        String weekStart = df.format(inputDate.with(FIRST_OF_WEEK));
        return weekStart;
    }

    /**
     * 获取当前时间本周结束日期
     */
    public static String getWeekEnd() {
        LocalDateTime inputDate = LocalDateTime.now();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        TemporalAdjuster LAST_OF_WEEK =
                TemporalAdjusters.ofDateAdjuster(localDate -> localDate.plusDays(DayOfWeek.SUNDAY.getValue() - localDate.getDayOfWeek().getValue()));
        String weekEnd = df.format(inputDate.with(LAST_OF_WEEK));
        return weekEnd;
    }

    /**
     * 取本月第1天
     * @return
     */
    public static LocalDate firstDayOfThisMonth(){
        return LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
    }

    /**
     * 取本月第n天
     * @return
     */
    public static LocalDate nDayOfThisMonth(int n){
        return  LocalDate.now().withDayOfMonth(n);
    }

    /**
     * 取本月最后一天
     * @return
     */
    public static LocalDate lastDayOfThisMonth(){
        return  LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
    }

    /**
     * 取之后多少天
     * @return
     */
    public static LocalDate afterDayOfThisMonth(int n){
        return LocalDate.now().plusDays(n);
    }

    /**
     * 判断闰年
     * @return
     */
    public static boolean isLeapYear(){
        return LocalDate.now().isLeapYear();
    }

    /**
     * 判断本月天数
     * @return
     */
    public static int days(){
        return LocalDate.now().lengthOfMonth();
    }

    /**
     * 判断是本周周几,返回 MONDAY,TUESDAY。。。
     * @return
     */
    public static DayOfWeek getDayOfWeek(){
        return LocalDate.now().getDayOfWeek();
    }

    /**
     * 当前日期月份
     * @return
     */
    public static int getMonthValue(){
        return LocalDate.now().getMonthValue();
    }

    /* getYear()    int    获取当前日期的年份
        getMonth()    Month    获取当前日期的月份对象
        getMonthValue()    int    获取当前日期是第几月
        getDayOfWeek()    DayOfWeek    表示该对象表示的日期是星期几
        getDayOfMonth()    int    表示该对象表示的日期是这个月第几天
        getDayOfYear()    int    表示该对象表示的日期是今年第几天
        withYear(int year)    LocalDate    修改当前对象的年份
        withMonth(int month)    LocalDate    修改当前对象的月份
        withDayOfMonth(int dayOfMonth)    LocalDate    修改当前对象在当月的日期
        isLeapYear()    boolean    是否是闰年
        lengthOfMonth()    int    这个月有多少天
        lengthOfYear()    int    该对象表示的年份有多少天(365或者366)
        plusYears(long yearsToAdd)    LocalDate    当前对象增加指定的年份数
        plusMonths(long monthsToAdd)    LocalDate    当前对象增加指定的月份数
        plusWeeks(long weeksToAdd)    LocalDate    当前对象增加指定的周数
        plusDays(long daysToAdd)    LocalDate    当前对象增加指定的天数
        minusYears(long yearsToSubtract)    LocalDate    当前对象减去指定的年数
        minusMonths(long monthsToSubtract)    LocalDate    当前对象减去注定的月数
        minusWeeks(long weeksToSubtract)    LocalDate    当前对象减去指定的周数
        minusDays(long daysToSubtract)    LocalDate    当前对象减去指定的天数
        compareTo(ChronoLocalDate other)    int    比较当前对象和other对象在时间上的大小,返回值如果为正,则当前对象时间较晚,
        isBefore(ChronoLocalDate other)    boolean    比较当前对象日期是否在other对象日期之前
        isAfter(ChronoLocalDate other)    boolean    比较当前对象日期是否在other对象日期之后
        isEqual(ChronoLocalDate other)    boolean    比较两个日期对象是否相等*/
/**
 * 获取传入时间前n天集合列表
 * @param time
 * @param n
 * @return
 */
public static List<String> getBeforeNDays(String time, Integer n) {
    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    LocalDate date = LocalDate.parse(time);
    List<String> dateList =  new ArrayList<>();
    for(int i=0;i<=n;i++){
        dateList.add(df.format(date.minusDays(i)));
    }
    Collections.reverse(dateList);
    return dateList;
}

/**
 * 获取一年有多少自然周
 * @param year
 * @return
 */
public static int getWeekNumByYear(int year){
    //初始化,第一周至少四天
    WeekFields wfs = WeekFields.of(DayOfWeek.MONDAY, 4);
    //一年最后一天日期的LocalDate,如果该天获得的周数为1或52,那么该年就只有52周,否则就是53周
    //获取指定时间所在年的周数
    int num= LocalDate.of(year, 12, 31).get(wfs.weekOfWeekBasedYear());
    num = num == 1 ? 52 : num;
    return num;
}

/**
 * 获取一年当中第多少周的日期列表
 * @param year
 * @param num
 * @return
 */
private static List<String> getDateByYearAndWeekNumAndDayOfWeek(Integer year, Integer num) {
    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    List<String> localDates = new ArrayList<>();
    for(int i=1;i<=DayOfWeek.values().length;i++){
        //周数小于10在前面补个0
        String numStr = num < 10 ? "0" + String.valueOf(num) : String.valueOf(num);
        //2019-W01-01获取第一周的周一日期,2019-W02-07获取第二周的周日日期
        String weekDate = String.format("%s-W%s-%s", year, numStr, i);
        localDates.add(df.format(LocalDate.parse(weekDate, DateTimeFormatter.ISO_WEEK_DATE)));
    }
    return localDates;
}

/**
 * 指定年份指定周的前n周(n<52)
 * @param year 年份
 * @param week 指定周
 * @param n 前多少周
 * @return 每周对应的时间日期
 */
public static List<Map<String,List<String>>> getWeekDateList(int year,int week,int n){
    //n>=52,跨了两年,不考虑
    if(n>=52){
        throw new RuntimeException("周跨度太长");
    }
    List<Map<String,List<String>>> returnList = new ArrayList<>();
    //不涉及跨年
    if(week > n){
        for(int i = week - n;i <= week;i++){
            Map<String,List<String>> map = new HashMap<>();
            List<String> localDates = getDateByYearAndWeekNumAndDayOfWeek(year,i);
            map.put( year + "第" + i + "周",localDates);
            returnList.add(map);
        }
    }
    //跨年
    else{
        //查询前一年有多少周
        int weekNum = getWeekNumByYear(year - 1);
        //前一年要计算的周数
        int k = n - week + 1;
        //前一年的周时间列表
        List<String> beforeLocalDates = new ArrayList<>();
        //当年的周时间列表
        List<String> localDates = new ArrayList<>();
        for(int i=weekNum - k + 1;i<=weekNum;i++){
            Map<String,List<String>> map = new HashMap<>();
            beforeLocalDates =  getDateByYearAndWeekNumAndDayOfWeek(year - 1,i);
            map.put( year - 1 + "第" + i + "周",beforeLocalDates);
            returnList.add(map);
        }
        for(int j=1;j<=week;j++){
            Map<String,List<String>> map = new HashMap<>();
            localDates =  getDateByYearAndWeekNumAndDayOfWeek(year,j);
            map.put( year + "第" + j + "周",localDates);
            returnList.add(map);
        }
    }
    return returnList;
}

/**
 * 获取指定月前n个月日期月份集合
 * @param year
 * @param month
 * @return
 */
public static List<String> getBeforeNMonth(int year,int month,int n){
    List<String> returnList = new ArrayList<>();
    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM");
    LocalDate monthDate = LocalDate.of(year, month,1);
    for(int i=0;i<=n;i++){
        returnList.add(df.format(monthDate.minusMonths(i))) ;
    }
    Collections.reverse(returnList);
    return returnList;
}

/**
 * 获取指定季度前n个季度日期季度集合
 * @param year 年份
 * @param quarter 季度
 * @param n 前多少季度
 * @return
 */
public static List<Map<String,List<String>>> getQuarterDate(int year,int quarter,int n){
    if(n > 3){
        throw new RuntimeException("季度跨度太长");
    }
    List<Map<String,List<String>>> returnList = new ArrayList<>();
    //不涉及跨年
    if(quarter > n){
        for(int i = quarter - n;i <= quarter;i++){
            Map<String,List<String>> map = new HashMap<>();
            List<String> localDates = getQuarterDateByYear(year,i);
            map.put( year + "第" + i + "季度",localDates);
            returnList.add(map);
        }
    }
    //跨年
    else{
        //前一年的季度时间列表
        List<String> beforeLocalDates = new ArrayList<>();
        //当年的季度时间列表
        List<String> localDates = new ArrayList<>();
        for(int i= quarter + 1;i <= n + 1;i++){
            Map<String,List<String>> map = new HashMap<>();
            beforeLocalDates =  getQuarterDateByYear(year - 1,i);
            map.put( year - 1 + "第" + i + "季度",beforeLocalDates);
            returnList.add(map);
        }
        for(int j=1;j<=quarter;j++){
            Map<String,List<String>> map = new HashMap<>();
            localDates = getQuarterDateByYear(year,j);
            map.put( year + "第" + j + "季度",localDates);
            returnList.add(map);
        }
    }
    return returnList;
}

/**
 * 获取年份季度日期集合
 * @param year
 * @param quarter
 * @return
 */
private static List<String> getQuarterDateByYear(int year, int quarter) {
    List<String> list = new ArrayList<>();
    switch (quarter){
        case 1:
            list.add(year + "-" + "01");
            list.add(year + "-" + "02");
            list.add(year + "-" + "03");
            break;
        case 2:
            list.add(year + "-" + "04");
            list.add(year + "-" + "05");
            list.add(year + "-" + "06");
            break;
        case 3:
            list.add(year + "-" + "07");
            list.add(year + "-" + "08");
            list.add(year + "-" + "09");
            break;
        case 4:
            list.add(year + "-" + "10");
            list.add(year + "-" + "11");
            list.add(year + "-" + "12");
            break;
        default:
            break;
    }
    return list;
}

/**
 * 获取传入年份的前n年集合,包括传入年份
 * @param year
 * @param n
 * @return
 */
public static List<String> getYearList(int year,int n){
    List<String> returnList = new ArrayList<>();
    for(int i = 0;i <= n;i++){
        returnList.add(String.valueOf(year - i));
    }
    Collections.reverse(returnList);
    return returnList;
}


    public static void main(String[] args) {
        System.out.println(getLocalDateTime(new Date()));
    }
}
  • 作者:胡小生99
  • 原文链接:https://blog.csdn.net/qq_37722992/article/details/106619309
    更新时间:2022年11月20日07:57:15 ,共 14487 字。