时间工具集

1、两日期差值

public static Integer getDayBetween(String day1, String day2) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = null;
        Date parse2 = null;
        try {
            parse = sdf.parse(day1);
            parse2 = sdf.parse(day2);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        long DAY1 = parse.getTime();
        long DAY2 = parse2.getTime();
        int day = (int) ((DAY1-DAY2) / (24 * 60 * 60 * 1000));
        return day;
    }

2、获取指定日期前n天日期

public static String getDay(String specifiedDate,int i) {
        // 使用DateTimeFormatter解析字符串日期
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date = LocalDate.parse(specifiedDate, formatter);

        // 获取前一天日期
        LocalDate previousDay = date.minusDays(i);

        // 输出结果
        System.out.println("指定日期:" + specifiedDate);
        System.out.println("前i天日期:" + previousDay.format(formatter));
        return previousDay.format(formatter);
    }

3、获取指定日期后n天日期

public static String getDayAfter(String specifiedDate,int i) {
        // 使用DateTimeFormatter解析字符串日期
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date = LocalDate.parse(specifiedDate, formatter);

        // 获取前一天日期
        LocalDate previousDay = date.plusDays(i);

        // 输出结果
        System.out.println("指定日期:" + specifiedDate);
        System.out.println("后i天日期:" + previousDay.format(formatter));
        return previousDay.format(formatter);
    }

4、获取两个日期之间的所有年

public static List<String> getYearBetweenDate(String startTime, String endTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        // 声明保存日期集合
        List<String> list = new ArrayList<>();
        try {
            // 转化成日期类型
            Date startDate = sdf.parse(startTime);
            Date endDate = sdf.parse(endTime);

            //用Calendar 进行日期比较判断
            Calendar calendar = Calendar.getInstance();
            while (startDate.getTime() <= endDate.getTime()) {

                // 把日期添加到集合
                list.add(sdf.format(startDate));

                // 设置日期
                calendar.setTime(startDate);

                //把年数增加 1
                calendar.add(Calendar.YEAR, 1);

                // 获取增加后的日期
                startDate = calendar.getTime();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

5、获取两个日期之间每隔10分钟的时间列表

public static List<String> getTimeList(LocalDateTime start, LocalDateTime end) {
        List<LocalDateTime> timeList = new ArrayList<>();
        List<String> timeList1 = new ArrayList<>();

        // 循环添加时间,直到超过结束时间
        LocalDateTime currentTime = start;
        while (!currentTime.isAfter(end)) {
            timeList.add(currentTime);
            // 加上10分钟
            currentTime = currentTime.plusMinutes(10);
        }

        // 如果结束时间正好是10分钟的倍数,也将其加入列表
        if (!timeList.contains(end)) {
            Date from = Date.from(end.atZone(ZoneId.systemDefault()).toInstant());
            String format = sdf.format(from);
            timeList1.add(format);
        }

        return timeList1;
    }

6、获取两个日期之间每隔30分钟的时间列表

public static List<String> getHalfHourlyTimes(LocalDateTime startTime, LocalDateTime endTime) {
        List<LocalDateTime> times = new ArrayList<>();
        List<String> timeList = new ArrayList<>();
        while (startTime.isBefore(endTime) || startTime.isEqual(endTime)) {
            times.add(startTime);
            Date from = Date.from(startTime.atZone(ZoneId.systemDefault()).toInstant());
            String format = sdf.format(from);
            timeList.add(format);
            startTime = startTime.plusMinutes(30);
        }
        return timeList;
    }

7、获取两个日期之间每隔一小时的时间列表

public static List<String> getHourlyList(LocalDateTime startDateTime, LocalDateTime endDateTime) {
        List<LocalDateTime> hourlyList = new ArrayList<>();
        List<String> timeList = new ArrayList<>();
        LocalDateTime currentDateTime = startDateTime;

        // 确保开始时间小于结束时间
        if (startDateTime.isAfter(endDateTime)) {
            LocalDateTime temp = startDateTime;
            startDateTime = endDateTime;
            endDateTime = temp;
        }

        // 遍历并添加每隔一小时的时间
        while (currentDateTime.isBefore(endDateTime) || currentDateTime.isEqual(endDateTime)) {
            hourlyList.add(currentDateTime);
            Date from = Date.from(currentDateTime.atZone(ZoneId.systemDefault()).toInstant());
            String format = sdf.format(from);
            timeList.add(format);
            currentDateTime = currentDateTime.plus(1, ChronoUnit.HOURS);
        }

        return timeList;
    }

8、获取两个日期之间每隔2小时的时间列表

public static List<String> getHoursBetweenDates(LocalDateTime startDateTime, LocalDateTime endDateTime, long hoursInterval) {
        List<LocalDateTime> hoursList = new ArrayList<>();
        List<String> timeList = new ArrayList<>();
        LocalDateTime currentDateTime = startDateTime;

        while (currentDateTime.isBefore(endDateTime) || currentDateTime.isEqual(endDateTime)) {
            hoursList.add(currentDateTime);
            Date from = Date.from(currentDateTime.atZone(ZoneId.systemDefault()).toInstant());
            String format = sdf.format(from);
            timeList.add(format);
            currentDateTime = currentDateTime.plusHours(hoursInterval);
        }

        return timeList;
    }

9、获取两个日期之间每隔一天的时间列表

public static List<String> getDatesBetween(LocalDateTime startDate, LocalDateTime endDate) {
        List<LocalDateTime> dates = new ArrayList<>();
        List<String> timeList = new ArrayList<>();
        while (!startDate.isAfter(endDate)) {
            dates.add(startDate);
            Date from = Date.from(startDate.atZone(ZoneId.systemDefault()).toInstant());
            String format = sdf.format(from);
            timeList.add(format);
            startDate = startDate.plusDays(1);
        }
        return timeList;
    }

10、切割日期。按照周期切割成小段日期段

/**
* 切割日期。按照周期切割成小段日期段。例如: <br>
*
* @param startDate 开始日期(yyyy-MM-dd)
* @param endDate 结束日期(yyyy-MM-dd)
* @param period 周期(天,周,月,年)
* @return 切割之后的日期集合
* @author zero 2019/04/02
* @example
*          <li>startDate="2019-02-28",endDate="2019-03-05",period="day"</li>
*          <li>结果为:[2019-02-28, 2019-03-01, 2019-03-02, 2019-03-03, 2019-03-04, 2019-03-05]</li><br>
*          <li>startDate="2019-02-28",endDate="2019-03-25",period="week"</li>
*          <li>结果为:[2019-02-28,2019-03-06, 2019-03-07,2019-03-13, 2019-03-14,2019-03-20,
*          2019-03-21,2019-03-25]</li><br>
*          <li>startDate="2019-02-28",endDate="2019-05-25",period="month"</li>
*          <li>结果为:[2019-02-28,2019-02-28, 2019-03-01,2019-03-31, 2019-04-01,2019-04-30,
*          2019-05-01,2019-05-25]</li><br>
*          <li>startDate="2019-02-28",endDate="2020-05-25",period="year"</li>
*          <li>结果为:[2019-02-28,2019-12-31, 2020-01-01,2020-05-25]</li><br>
*/

public static List<String> getPieDateRange(String startDate, String endDate, String period) {
        List<String> result = Lists.newArrayList();
        LocalDate end = LocalDate.parse(endDate, yyyyMMdd_EN);
        LocalDate start = LocalDate.parse(startDate, yyyyMMdd_EN);
        LocalDate tmp = start;
        switch (period) {
            case DAY:
                while (start.isBefore(end) || start.isEqual(end)) {
                    result.add(start.toString());
                    start = start.plusDays(1);
                }
                break;
            case WEEK:
                while (tmp.isBefore(end) || tmp.isEqual(end)) {
                    if (tmp.plusDays(6).isAfter(end)) {
                        result.add(tmp.toString() + "," + end);
                    } else {
                        result.add(tmp.toString() + "," + tmp.plusDays(6));
                    }
                    tmp = tmp.plusDays(7);
                }
                break;
            case MONTH:
                while (tmp.isBefore(end) || tmp.isEqual(end)) {
                    LocalDate lastDayOfMonth = tmp.with(TemporalAdjusters.lastDayOfMonth());
                    if (lastDayOfMonth.isAfter(end)) {
                        result.add(tmp.toString() + "," + end);
                    } else {
                        result.add(tmp.toString() + "," + lastDayOfMonth);
                    }
                    tmp = lastDayOfMonth.plusDays(1);
                }
                break;
            case YEAR:
                while (tmp.isBefore(end) || tmp.isEqual(end)) {
                    LocalDate lastDayOfYear = tmp.with(TemporalAdjusters.lastDayOfYear());
                    if (lastDayOfYear.isAfter(end)) {
                        result.add(tmp.toString() + "," + end);
                    } else {
                        result.add(tmp.toString() + "," + lastDayOfYear);
                    }
                    tmp = lastDayOfYear.plusDays(1);
                }
                break;
            default:
                break;
        }
        return result;
    }

11、获取输入月最大日期

/**
     * 获取输入月最大日期
     *
     * @param time "2022-11"
     * @return
     */
    public static int getMaxDateNum(String time) {
        Calendar c = Calendar.getInstance();
        String[] split = time.split("-");
        c.set(Calendar.YEAR, Integer.parseInt(split[0]));
        c.set(Calendar.MONTH, Integer.parseInt(split[1]) - 1);
        c.set(Calendar.DATE, 1);
        c.roll(Calendar.DATE, -1);
        return c.get(Calendar.DATE);
    }

12、传入两个时间范围,返回这两个时间范围内的所有日期,并保存在一个集合中

/**
     * 传入两个时间范围,返回这两个时间范围内的所有日期,并保存在一个集合中
     *
     * @param beginTime
     * @param endTime
     * @return
     * @throws Exception
     */
    public static List<String> findEveryDay(String beginTime, String endTime) {
        //创建一个放所有日期的集合
        List<String> dates = new ArrayList();
        //创建时间解析对象规定解析格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //将传入的时间解析成Date类型,相当于格式化
        Date dBegin = null;
        try {
            dBegin = sdf.parse(beginTime);
            Date dEnd = sdf.parse(endTime);
            //将格式化后的第一天添加进集合
            dates.add(sdf.format(dBegin));
            //使用本地的时区和区域获取日历
            Calendar calBegin = Calendar.getInstance();
            //传入起始时间将此日历设置为起始日历
            calBegin.setTime(dBegin);
            //判断结束日期前一天是否在起始日历的日期之后
            while (dEnd.after(calBegin.getTime())) {
                //根据日历的规则:月份中的每一天,为起始日历加一天
                calBegin.add(Calendar.DAY_OF_MONTH, 1);
                //得到的每一天就添加进集合
                dates.add(sdf.format(calBegin.getTime()));
                //如果当前的起始日历超过结束日期后,就结束循环
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dates;
    }

13、获取两个日期之间的所有月份 (年月)

/**
     * 获取两个日期之间的所有月份 (年月)
     *
     * @param startTime
     * @param endTime
     * @return:list
     */
    public static List<String> getMonthBetweenDate(String startTime, String endTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        // 声明保存日期集合
        List<String> list = new ArrayList<>();
        try {
            // 转化成日期类型
            Date startDate = sdf.parse(startTime);
            Date endDate = sdf.parse(endTime);
            //用Calendar 进行日期比较判断
            Calendar calendar = Calendar.getInstance();
            while (startDate.getTime() <= endDate.getTime()) {
                // 把日期添加到集合
                list.add(sdf.format(startDate));
                // 设置日期
                calendar.setTime(startDate);
                //把月数增加 1
                calendar.add(Calendar.MONTH, 1);
                // 获取增加后的日期
                startDate = calendar.getTime();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

14、获取两个日期之间的所有年

/**
     * 获取两个日期之间的所有年
     *
     * @param startTime
     * @param endTime
     * @return:list
     */
    public static List<String> getYearBetweenDate(String startTime, String endTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        // 声明保存日期集合
        List<String> list = new ArrayList<>();
        try {
            // 转化成日期类型
            Date startDate = sdf.parse(startTime);
            Date endDate = sdf.parse(endTime);
            //用Calendar 进行日期比较判断
            Calendar calendar = Calendar.getInstance();
            while (startDate.getTime() <= endDate.getTime()) {
                // 把日期添加到集合
                list.add(sdf.format(startDate));
                // 设置日期
                calendar.setTime(startDate);
                //把年数增加 1
                calendar.add(Calendar.YEAR, 1);
                // 获取增加后的日期
                startDate = calendar.getTime();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

15、将时间转换为时间戳

public static String dateToStamp(String s){
        String res = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = simpleDateFormat.parse(s);
            long ts = date.getTime();
            res = String.valueOf(ts);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return res;
    }

16、将时间戳转换为时间

public static String stampToDate(String s){
        String res = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            long lt = new Long(s);
            Date date = new Date(lt);
            res = simpleDateFormat.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

17、计算两个日期字符串之间相差多少个周期(天,月,年)

/**
     * 计算两个日期字符串之间相差多少个周期(天,月,年)
     *
     * @param date1 yyyy-MM-dd
     * @param date2 yyyy-MM-dd
     * @param node 三者之一:(day,month,year)
     * @return 相差多少周期
     * @author zero 2019/03/31
     */
    public static int peridCount(String date1, String date2, String node) {
        date1 = date1.trim();
        date2 = date2.trim();
        if (DAY.equals(node)) {
            return Period.between(LocalDate.parse(date1), LocalDate.parse(date2)).getDays();
        } else if (MONTH.equals(node)) {
            return Period.between(LocalDate.parse(date1), LocalDate.parse(date2)).getMonths();
        } else if (YEAR.equals(node)) {
            return Period.between(LocalDate.parse(date1), LocalDate.parse(date2)).getYears();
        } else {
            return 0;
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值