当前位置: 首页 > news >正文

java根据时间区间计算区间中都包含那几个月

在一些需要统计类的需求中可能会计算同比/环比数据,往往我们拿到的并不是每个月的准确时间,需要自行计算,一点一点计算还是挺麻烦的,因此搞一个工具类出来

工具类 

public static void main(String[] args) {
        //为了准确,这里使用的时间毫秒值
        long beginTime = 1577836800000L;
        long endTime = 1700994771650L;
        // 将毫秒值转换为Instant对象
        Instant startInstant = Instant.ofEpochMilli(beginTime);
        Instant endInstant = Instant.ofEpochMilli(endTime);
        // 转换为LocalDate对象
        LocalDate startDate = startInstant.atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate endDate = endInstant.atZone(ZoneId.systemDefault()).toLocalDate();
        // 计算每个月的时间区间
        LocalDate currentMonthStart = startDate.withDayOfMonth(1);
        while (!currentMonthStart.isAfter(endDate)) {
            LocalDate currentMonthEnd = currentMonthStart.plusMonths(1).minusDays(1);
            // 处理结束时间在下个月的情况
            if (currentMonthEnd.isAfter(endDate)) {
                currentMonthEnd = endDate;
            }
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            System.out.println("开始时间:" + currentMonthStart.format(formatter) + "    结束时间:" + currentMonthEnd.format(formatter));
            // 移动到下个月的开始
            currentMonthStart = currentMonthStart.plusMonths(1);
        }
    }

测试结果

相关文章:

  • 【点云surface】 凹包重构
  • 改进YOLOv8 | YOLOv5系列:RFAConv续作,即插即用具有任意采样形状和任意数目参数的卷积核AKCOnv
  • Linux MMC子系统 - 6.eMMC 5.1工作模式-设备识别模式
  • Unity-链接MySql8.0
  • [网络] 字节一面~ 2. HTTP 2 与 HTTP 1.x 有什么区别
  • SpringMVC(三)
  • flink sqlClient提交hiveIceberg
  • 日志配置的一些思考
  • 1.前端--基本概念【2023.11.25】
  • 【DevOps】Git 图文详解(九):工作中的 Git 实践
  • 网络篇---第一篇
  • ubuntu 使用快照启动polygon主网
  • Linux内核--内存管理(四)CPU缓存
  • 【开源】基于Vue+SpringBoot的农家乐订餐系统
  • C语言——单链表(增删改查)
  • Java枚举
  • Kafka-TopicPartition
  • 一键下载Python各版本中的最新版
  • 通用功能——git 攻略
  • 什么是轻量应用服务器?可以从亚马逊云科技的优势入手了解
  • 季后赛主场优势消失之谜,这事竟然要赖库里
  • “海豚音”依旧互动更多,玛丽亚·凯莉本周来沪开唱
  • 均价19.5万元/平米!上海徐汇滨江地王项目“日光”,销售额近70亿元
  • 悬疑推理联合书单|虫神山事件
  • “一嗨租车”陷“五年后扣费”疑云,用户:违章处理莫名消失
  • 铲屎官花5万带猫狗旅行,宠旅生意有多赚?