Java 获取当前时间周数,及根据周数获取周的起止时间

package com.hr.weekly.controller;

import com.hr.weekly.utils.DateUtil;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author cc
 * @data 2022年03月16日 11:13
 */
public class Test {

    public static void main(String[] args) throws ParseException {
        //当前时间
        Date newDate = new Date();
        //开始时间
        Date parse = DateUtil.parse("2022-1-1 00:00:00");
        dateWeek(parse);
        getWeekDays(2021, 52);
    }

    public static void dateWeek(Date d) {
        Calendar c = Calendar.getInstance();
        // 设置每周的开始日期
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.setTime(d);
        c.setMinimalDaysInFirstWeek(7);
        String getCurrentTime=new SimpleDateFormat("yyyy-MM-dd ").format(c.getTime());
        System.out.println(getCurrentTime);//年-月-日
        String getCurrent1=new SimpleDateFormat("yyyy-MM ").format(c.getTime());
        System.out.println(getCurrent1);//年-月
        System.out.println("当前时间 年-月-日:" + new SimpleDateFormat("yyyy-MM-dd ").format(c.getTime()));
        System.out.println("当前时间 年-月-日 时:分:秒:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(c.getTime()));
        System.out.println("当前时间的年份:" + c.get(Calendar.YEAR));//获取当前年
        System.out.println("当前时间的月份:" + (c.get(Calendar.MONTH) + 1));
        System.out.println("当前时间的年周数:" + c.get(Calendar.WEEK_OF_YEAR));
        //判断周数如果为52,月份不为12月,则代表跨年周,所属年份需减一
        if(c.get(Calendar.WEEK_OF_YEAR) == 52 && (c.get(Calendar.MONTH) + 1) < 12){
            System.out.println("当前时间周数所属年份:" + (c.get(Calendar.YEAR) -1 ));
        }else {
            System.out.println("当前时间周数所属年份:" + c.get(Calendar.YEAR));
        }
    }


    /**
     * 根据具体年份周数获取日期范围
     * @param year
     * @param week
     * @return
     */
    public static void getWeekDays(int year, int week) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal=Calendar.getInstance();
        // 设置每周的开始日期
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        cal.setMinimalDaysInFirstWeek(7);
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.WEEK_OF_YEAR, week);
        cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
        String beginDate = sdf.format(cal.getTime());

        cal.add(Calendar.DAY_OF_WEEK, 6);
        String endDate = sdf.format(cal.getTime());
        System.out.println(year+"年第"+ week + "周起止时间:");
    }
}

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