轻松搞定-根据当前日期获取今日、昨日、本周、上周、本月、上月开始结束时间

 1.只需要传入type参数,即可自动判断得出开始结束时间:

type:今日:today、昨日:yesterday、本周:thisweek、上周:lastweek、本月:thismonth、

上月:lastmonth

private Map getDateByType(String type){
    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    //TODO 获取当前时间
    LocalDate inputDate = LocalDate.now();

    //当天
    String todayMin = LocalDateTime.of(inputDate, LocalTime.MIN).format(df);
    String todayMax = LocalDateTime.of(inputDate, LocalTime.MAX).format(df);

    //前一天
    String yestDayMin = LocalDateTime.of(inputDate, LocalTime.MIN).plusDays(-1).format(df);
    String yestDayMax = LocalDateTime.of(inputDate, LocalTime.MAX).plusDays(-1).format(df);

    //当周
    String weekMin = LocalDateTime.of(inputDate.with(DayOfWeek.MONDAY), LocalTime.MIN).format(df);
    String weekMax = LocalDateTime.of(inputDate.with(DayOfWeek.SUNDAY), LocalTime.MAX).format(df);

    //上周
    String weekMin1 = LocalDateTime.of(inputDate.with(DayOfWeek.MONDAY), LocalTime.MIN).plusWeeks(-1).format(df);
    String weekMax1 = LocalDateTime.of(inputDate.with(DayOfWeek.SUNDAY), LocalTime.MAX).plusWeeks(-1).format(df);

    //当月
    String monMin = LocalDateTime.of(inputDate.with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN).format(df);
    String monMax = LocalDateTime.of(inputDate.with(TemporalAdjusters.lastDayOfMonth()), LocalTime.MAX).format(df);

    //上个月
    String monMin1 = LocalDateTime.of(inputDate.with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN).plusMonths(-1).format(df);
    String monMax1 = LocalDateTime.of(inputDate.with(TemporalAdjusters.lastDayOfMonth()), LocalTime.MAX).plusMonths(-1).format(df);
    Map dateMap =  Maps.newHashMap();
    String begin="";
    String end="";
    switch (type){
        case "today":
            begin=todayMin;
            end=todayMax;
            break;
        case "yesterday":
            begin=yestDayMin;
            end=yestDayMax;
            break;
        case "thisweek":
            begin=weekMin;
            end=weekMax;
            break;
        case "lastweek":
            begin=weekMin1;
            end=weekMax1;
            break;
        case "thismonth":
            begin=monMin;
            end=monMax;
            break;
        case "lastmonth":
            begin=monMin1;
            end=monMax1;
            break;
        default :
            begin="1970-01-01";
            end=todayMax;
    }
    dateMap.put("begin",begin);
    dateMap.put("end",end);
    return dateMap;
}

你可能感兴趣的:(JAVA,java)