获取时间区间中所有的日期 对象过滤去重

public static void main(String[] args) {
        TimeParam startTime = new TimeParam().getInstance(aopBase.getStartTime());         TimeParam endTime = new TimeParam().getInstance(aopBase.getStartTime());         List<LocalDate> localDateList =         TimeParam.getAllDatesInTheDateRange(LocalDate.of(startTime.getYear(),         startTime.getMonth(), startTime.getDay()), LocalDate.of(endTime.getYear(),         endTime.getMonth(), endTime.getDay()));
        if (CollectionUtils.isNotEmpty(localDateList)) {
            localDateList.forEach(System.out::println);
        }
}
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * @author LiuQi
 * @version 1.0
 * @data 2022/12/8 15:07
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class TimeParam
{
    private Integer year;
    private Integer month;
    private Integer day;


    public TimeParam getInstance(String time)
    {
        String replaceAll = time.replaceAll("-", "");
        Integer year = Integer.parseInt(replaceAll.substring(0, 4));
        Integer month = Integer.parseInt(replaceAll.substring(4, 6));
        Integer day = Integer.parseInt(replaceAll.substring(6,8));
        TimeParam build = this.builder()
                .year(year)
                .month(month)
                .day(day)
                .build();
        return build;
    }

    /**
     * 根据传入的日期,获取时间区间中所有的日期
     *
     * @param startDate 开始日期
     * @param endDate 结束日期
     */
    public static List<LocalDate> getAllDatesInTheDateRange(LocalDate startDate, LocalDate endDate) {
        List<LocalDate> localDateList = new ArrayList<>();
     
        if (startDate.isAfter(endDate)) { // 开始时间必须小于结束时间
            return null;
        }
        while (startDate.isBefore(endDate)) {
            localDateList.add(startDate);
            startDate = startDate.plusDays(1);
        }
        localDateList.add(endDate);
        return localDateList;
    }

    /**
     * 过滤重复对象
     * @param keyExtractor
     * @return
     * @param <T>
     */
    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object, Boolean> hashMap = new ConcurrentHashMap<>();
        return result -> hashMap.putIfAbsent(keyExtractor.apply(result), Boolean.TRUE) == null;
    }
}


                
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值