栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Java

Calendar类的使用

Java 更新时间:发布时间: 百科书网 趣学号
Time.java
package org.example.testcalendar;

public class Time {
    public static final long SEC = 1000L;
    public static final long MIN = 60 * SEC;
    public static final long HOUR = 60 * MIN;
    public static final long DAY = 24 * HOUR;
    public static final long WEEK = 7 * DAY;
}
CalendarService.java
package org.example.testcalendar;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class CalendarService {
    
    public static int getCurMonthTotalDays() {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(System.currentTimeMillis());
        return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
    }


    
    public static long getNextNearWeekDayTime(String timeFormat, int weekDay) {
        String yyyyMMddHHmmss = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(yyyyMMddHHmmss);

        // 策划配置的开始时间
        long confStartTime = -1;
        try {
            timeFormat = timeFormat.replace(":", ":");
            confStartTime = sdf.parse(timeFormat).getTime();
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        // 得到配置的时间
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(confStartTime);

        int dayIndex = -1;
        if (weekDay == 7) {
            dayIndex = 1;
        } else {
            dayIndex = weekDay + 1;
        }

        // 设置为周六,为计算最近的周六做准备
        cal.set(Calendar.DAY_OF_WEEK, dayIndex);

        long startInWeekDayTime = cal.getTimeInMillis();
        // 保证实际开始时间一定在配置时间之后
        if (startInWeekDayTime < confStartTime) {
            startInWeekDayTime += Time.WEEK;
        }

        return startInWeekDayTime;
    }
}

Main.java

package org.example.testcalendar;

public class Main {
    public static void main(String[] args) {
        int curMonthTotalDays = CalendarService.getCurMonthTotalDays();
        System.out.println("这个月天数=" + curMonthTotalDays);

        long realStartWeekDayTime = CalendarService.getNextNearWeekDayTime("2021-09-29 00:00:00", 6);
        System.out.println(realStartWeekDayTime);
    }
}

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/273646.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号