java 中 使用 jodatime 获取一段时间内的星期集合

一、应用场景

公司做统计相关业务总会用到一些和时间相关处理,java7的canlendar用着实在太难受了,java8的我没有研究过,我不知道前端处理日历是否简单,我这边都是处理好返回前台,直接调用就好了

二、实例

1、引入jodatime


    joda-time
    joda-time
    2.9.9
       

2、controller

/***
 * 日期controller
 * @author wx
 * @Date 2019-02-14
 */
@RestController
@RequestMapping("/api/datetime")
public class DateTimeController {


    /**
     * 获取一段时间内的星期集合
     * @param startDate
     * @param endDate
     * @param req
     * @param resp
     * @return
     */
    @GetMapping("/getWeekListByDates")
    public BaseRetBean getWeekListByDates(@RequestParam(value = "startDate",required = true)String startDate,
                                          @RequestParam(value = "endDate",required = true)String endDate,
                                          HttpServletRequest req, HttpServletResponse resp){
        BaseRetBean baseRetBean = new BaseRetBean();
        baseRetBean.setRet(1);
        baseRetBean.setMsg("成功");
        baseRetBean.setRows(this.converWeekList(new LocalDate(startDate),new LocalDate(endDate)));
        return baseRetBean;
    }

    /**
     * 获取本月星期集合
     * @param req
     * @param resp
     * @return
     */
    @GetMapping("/getLocalMonthWeekList")
    public BaseRetBean getLocalMonthWeekList(HttpServletRequest req, HttpServletResponse resp){
        BaseRetBean baseRetBean = new BaseRetBean();
        baseRetBean.setRet(1);
        baseRetBean.setMsg("成功");

        LocalDate now = LocalDate.now();
        LocalDate endDate = now.dayOfMonth().withMaximumValue();
        LocalDate startDate = now.dayOfMonth().withMinimumValue();
        baseRetBean.setRows(this.converWeekList(startDate,endDate));
        return baseRetBean;
    }

    /**
     * 转换weeklist
     * @param startDate
     * @param endDate
     * @return
     */
    private List converWeekList(LocalDate startDate,LocalDate endDate){

        List weekList = new ArrayList<>();
        //转换成joda-time的对象
        LocalDate firstDay = startDate.dayOfWeek().withMinimumValue();
        LocalDate lastDay = endDate.dayOfWeek().withMaximumValue();
        //计算两日期间的区间天数
        Period p = new Period(firstDay, lastDay, PeriodType.days());
        int days = p.getDays();
        if (days > 0){
            int weekLength = 7;
            for(int i=0;i

参考文章:
https://blog.csdn.net/x3455/article/details/80593319
https://www.jianshu.com/p/0459c71930df
https://www.jianshu.com/p/efdeda608780
-end-

你可能感兴趣的:(java 中 使用 jodatime 获取一段时间内的星期集合)