工作中java常用的时间工具类:Calendar

18 篇文章 0 订阅
 /**
     * 根据传参求出对应月份的最后一天
     */
    @Test
    public void setAndGetRangeEndTime() {
        int index = 1;
        //int range=2;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        //昨天
        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 1);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        //月份
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - index);
        //月份最大天数
        int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        calendar.set(Calendar.DAY_OF_MONTH, maxDay);
        String format = sdf.format(calendar.getTime());
        System.out.println("结果:" + format);
    }


    /**
     * 补全开始到结束时间的工具方法
     */
    public List<String> testDateUtils(String startTime, String endTime) throws Exception {

        startTime = "2021-02-03";
        endTime = "2021-02-06";

        if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)) {
            throw new Exception("开始日期和截止日期都不能为空!");
        }
        //compareTo 当两者相等时为0,当前者小于后者时返回-1,大于时返回1。具体查看源码。
        if (startTime.compareTo(endTime) > 0) {
            throw new Exception("开始日期必须小于等于截止日期!");
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = simpleDateFormat.parse(startTime);
        Date endDate = simpleDateFormat.parse(endTime);

        Calendar startCal = Calendar.getInstance();
        Calendar endCal = Calendar.getInstance();
        startCal.setTime(startDate);
        endCal.setTime(endDate);

        List<String> days = new ArrayList<>();
        //当开始时间大于结束时间时则返回
        while (startCal.compareTo(endCal) <= 0) {
            days.add(simpleDateFormat.format(startCal.getTime()));
            //Date本身加减日期过于麻烦,使用Calendar操纵日期;开始时间+1;
            startCal.add(Calendar.DATE, 1);

        }
        return days;

    }
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你可以叫我老白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值