获取指定年月开始和结束时间

获取指定年月开始结束时间
工具类: cn.hutool.core.date.DateUtil

    public static void main(String[] args) {
        for (int i = 1;i<13 ;i++) {
            //获取当月开始时间
            DateTime dateTime = DateUtil.beginOfMonth(DateUtil.parse("2022"+"-"+i, "yyyy-MM"));
            //获取当月结束时间
            DateTime dateTime1 = DateUtil.endOfMonth(DateUtil.parse("2022"+"-"+i, "yyyy-MM"));
            //DateTime转换为Date
            Date date = dateTime.toJdkDate();
            //Date转换为DateTime
            DateTime dateTime2 = new DateTime(date);
            //DateTime.toJdkDate()封装的就是new Date(dateTime.getTime());
            Date date1 = new Date(dateTime.getTime());
            System.out.println("2022年"+i+"月");
            System.out.println(dateTime+"\t\t\t\t"+i);
            System.out.println(dateTime1+"\t\t\t\t"+i);
            System.out.println(date+"\t"+i+"\n");
        }
        //直接用Calendar获取当月结束时间
        Calendar instance = Calendar.getInstance();
        instance.set(Calendar.YEAR,2022);
        instance.set(Calendar.MONTH,12);//月份取值范围[0,11]
        instance.set(Calendar.DATE,instance.getActualMaximum(Calendar.DATE));
        instance.set(Calendar.HOUR_OF_DAY, 23);
        instance.set(Calendar.MINUTE, 59);
        instance.set(Calendar.SECOND, 59);
        Date time = instance.getTime();
        System.out.println("Calendar获取"+DateUtil.formatDateTime(time));
    }

控制台打印

202212022-01-01 00:00:00				1
2022-01-31 23:59:59				1
Sat Jan 01 00:00:00 CST 2022	1

202222022-02-01 00:00:00				2
2022-02-28 23:59:59				2
Tue Feb 01 00:00:00 CST 2022	2

202232022-03-01 00:00:00				3
2022-03-31 23:59:59				3
Tue Mar 01 00:00:00 CST 2022	3

202242022-04-01 00:00:00				4
2022-04-30 23:59:59				4
Fri Apr 01 00:00:00 CST 2022	4

202252022-05-01 00:00:00				5
2022-05-31 23:59:59				5
Sun May 01 00:00:00 CST 2022	5


202262022-06-01 00:00:00				6
2022-06-30 23:59:59				6
Wed Jun 01 00:00:00 CST 2022	6

202272022-07-01 00:00:00				7
2022-07-31 23:59:59				7
Fri Jul 01 00:00:00 CST 2022	7

202282022-08-01 00:00:00				8
2022-08-31 23:59:59				8
Mon Aug 01 00:00:00 CST 2022	8

202292022-09-01 00:00:00				9
2022-09-30 23:59:59				9
Thu Sep 01 00:00:00 CST 2022	9

2022102022-10-01 00:00:00				10
2022-10-31 23:59:59				10
Sat Oct 01 00:00:00 CST 2022	10

2022112022-11-01 00:00:00				11
2022-11-30 23:59:59				11
Tue Nov 01 00:00:00 CST 2022	11

2022122022-12-01 00:00:00				12
2022-12-31 23:59:59				12
Thu Dec 01 00:00:00 CST 2022	12

Calendar获取2023-01-31 23:59:59

你可能感兴趣的:(java,开发语言)