java8获取今日,本周,本月,本季度,本年的开始时间,结束时间

713 阅读1分钟
 /**
     * 获取本周的第一天或最后一天
     * 
     * @param : [today, isFirst: true 表示开始时间,false表示结束时间]
     * @return
     */
    public static String getStartOrEndDayOfWeek(LocalDate today, Boolean isFirst) {
        LocalDate resDate = LocalDate.now();
        if (today == null) {
            today = resDate;
        }
        DayOfWeek week = today.getDayOfWeek();
        int value = week.getValue();
        if (isFirst) {
            resDate = today.minusDays(value - 1);
        } else {
            resDate = today.plusDays(7 - value);
        }
        return resDate.toString();
    }
/**
 * 获取本月的第一天或最后一天
 *
 * @Param: [today, isFirst: true 表示开始时间,false表示结束时间]
 * @return
 */
public static String getStartOrEndDayOfMonth(LocalDate today, Boolean isFirst) {
    LocalDate resDate = LocalDate.now();
    if (today == null) {
        today = resDate;
    }
    Month month = today.getMonth();
    int length = month.length(today.isLeapYear());
    if (isFirst) {
        resDate = LocalDate.of(today.getYear(), month, 1);
    } else {
        resDate = LocalDate.of(today.getYear(), month, length);
    }
    return resDate.toString();
}
/**
 * 获取本季度的第一天或最后一天
 * 
 * @param : [today, isFirst: true 表示开始时间,false表示结束时间]
 * @return
 */
public static String getStartOrEndDayOfQuarter(LocalDate today, Boolean isFirst) {
    LocalDate resDate = LocalDate.now();
    if (today == null) {
        today = resDate;
    }
    Month month = today.getMonth();
    Month firstMonthOfQuarter = month.firstMonthOfQuarter();
    Month endMonthOfQuarter = Month.of(firstMonthOfQuarter.getValue() + 2);
    if (isFirst) {
        resDate = LocalDate.of(today.getYear(), firstMonthOfQuarter, 1);
    } else {
        resDate = LocalDate.of(today.getYear(), endMonthOfQuarter, endMonthOfQuarter.length(today.isLeapYear()));
    }
    return resDate.toString();
}
  /**
     * 获取本年的第一天或最后一天
     * 
     * @param : [today, isFirst: true 表示开始时间,false表示结束时间]
     * @return
     */
    public static String getStartOrEndDayOfYear(LocalDate today, Boolean isFirst) {
        LocalDate resDate = LocalDate.now();
        if (today == null) {
            today = resDate;
        }
        if (isFirst) {
            resDate = LocalDate.of(today.getYear(), Month.JANUARY, 1);
        } else {
            resDate = LocalDate.of(today.getYear(), Month.DECEMBER, Month.DECEMBER.length(today.isLeapYear()));
        }
        return resDate.toString();
    }