当前位置: 首页 > 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);
        }
    }

测试结果

http://www.dtcms.com/a/4665.html

相关文章:

  • 【点云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 攻略
  • 什么是轻量应用服务器?可以从亚马逊云科技的优势入手了解
  • QT visual stdio加载动态库报错126问题
  • (附源码)SSM环卫人员管理平台 计算机毕设36412
  • 软件测试职业规划导图
  • 【漏洞复现】Array VPN任意文件读取漏洞
  • 系统架构设计:8 论软件架构风格
  • 【数据库篇】关系模式的表示——(2)规范化
  • UVA1025 城市里的间谍 A Spy in the Metro
  • 【深度学习】如何选择神经网络的超参数
  • 《微信小程序从入门到精通》---笔记1
  • 百战python04-循环结构