JAVA计算学校学期周次

package com.zs.create.test;

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

public class Test {
    public static void main(String[] args) throws ParseException {
        // 获取今年一年的总周次
        System.out.println(school_week("2020-08-31","2021-03-01","2021-01-04"));
    }

    /**
     * 根据第一学期开学时间 <br>
     * 第二学期开学时间<br>
     * 现在时间<br>
     * 计算当前时间的周次<br>
     * @param firstSemesterStr - 第一学期开学时间
     * @param secondSemesterStr - 第二学期开学时间
     * @param nowDateStr - 当前时间
     * @return 当前学期下的周次
     * @deprecated 参数必须要 yyyy-MM-dd 字符串格式
     * */
    public static int school_week(String firstSemesterStr, String secondSemesterStr, 
                                  String nowDateStr) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy");
        Date firstSemester = sdf.parse(firstSemesterStr);
        Date secondSemester = sdf.parse(secondSemesterStr);
        Date nowDate = sdf.parse(nowDateStr);
        Date nodeTime = sdf.parse(sdf1.format(firstSemester) + "-12-31");
        if (nowDate.getTime()>firstSemester.getTime() && nowDate.getTime() 
        < secondSemester.getTime()){
            //第一学期
            if(nowDate.getTime()>nodeTime.getTime()){
                // 出现跨年情况
                if (Current_week(nowDate.getTime()) == Current_week(nodeTime.getTime())){
                    return Current_week(nodeTime.getTime())-Current_week(firstSemester.getTime())+1;
                }
                return (Current_week(nodeTime.getTime()) + Current_week(nowDate.getTime())) 
                        - Current_week(firstSemester.getTime())+1;
            }else{
                // 没有跨年
                return Current_week(nowDate.getTime())-Current_week(firstSemester.getTime())+1;
            }
        }else {
            // 第二学期
            return Current_week(nowDate.getTime())-Current_week(secondSemester.getTime())+1;
        }
    }

    /**
     * @param time - 时间戳
     * @return 回当前时间所在年的周次
     * */
    public static int Current_week(long time) {
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);//设置星期一为一周开始的第一天
        calendar.setMinimalDaysInFirstWeek(4);//可以不用设置
        calendar.setTimeInMillis(time);//时间戳
        int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);//获得当前日期属于今年的第几周
        return weekOfYear;
    }
}
bystart

bystart

青檬小栈

留下你的评论

快留下你的小秘密吧