取两个时间段内天数

方式一 时间戳

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *  取两个时间段内天数
 */
public class test1 {

    public static void main(String[] args) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date star = dateFormat.parse("2020-02-03");//开始时间
            Date endDay=dateFormat.parse("2025-03-02");//结束时间
            Long starTime=star.getTime();
            System.out.println("开始时间:"+starTime);  // 时间戳:毫秒级,1s=1000ms
            Long endTime=endDay.getTime();
            System.out.println("结束时间:"+endTime);
            Long num=endTime-starTime;//时间戳相差的毫秒数
            System.out.println("相差天数为:"+num/24/60/60/1000);//除以一天的毫秒数
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

}

在这里插入图片描述

方式一方法抽取:
在这里插入图片描述

    private int diffDays(String dateStart, String dateEnd) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date startDate = dateFormat.parse(dateStart.trim().substring(0, 8));
        Date endDate = dateFormat.parse(dateEnd.trim().substring(0, 8));
        return Math.abs((int) ((endDate.getTime() - startDate.getTime()) / (24 * 60 * 60 * 1000)));
    }

方式二 util包的Calendar类

    // 第二种:试用util包的Calendar类,每次增加一天,直到和结束时间相等的时候。
    @Test
    public void demo2() throws ParseException {

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date star = dateFormat.parse("2020-02-03");
        Date endDay = dateFormat.parse("2025-03-02");
        Date nextDay = star;
        int i = 0;
        while (nextDay.before(endDay)){ // 当明天不在结束时间之前时终止循环
            Calendar cld = Calendar.getInstance();
            cld.setTime(star);
            cld.add(Calendar.DATE,1);
            star = cld.getTime();
            // 获取下一天日期字符串
            nextDay = star;
            i++;
        }
        System.out.println("相差天数为:"+i);
    }

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

码元宋大米

感谢小主大赏,留言可进互助群~

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

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

打赏作者

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

抵扣说明:

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

余额充值