Java获取时间几月第几周

import java.time.*;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;


/**
 * @author yxl
 * @version 1.0
 * @date 2021/12/06
 */
public class WeekUtil {


    /**
     * 根据时间获取月的第几周
     * @param sourceTime
     * @return
     */
    public static String getMonthNoAndWeekNo(LocalDateTime sourceTime) {
        Date date = Date.from(sourceTime.atZone(ZoneId.systemDefault()).toInstant());
        return join(date);
    }

    /**
     * 根据时间获取月的第几周
     * @param sourceTime
     * @return
     */
    public static String getMonthNoAndWeekNo(LocalDate sourceTime) {
        Date date = Date.from(sourceTime.atStartOfDay(ZoneOffset.ofHours(8)).toInstant());
        return join(date);
    }

    /**
     * 根据时间获取月的第几周
     * @param date
     * @return
     */
    public static String getMonthNoAndWeekNo(Date date) {
        return join(date);
    }

    /**
     * 拼接
     * @param date
     * @return
     */
    public static String join(Date date){
        return getMonth(date) + "-" + getWeek(date);
    }

    /**
     * 获取第几月
     * @param date 时间
     * @return
     */
    public static int getMonth(Date date) {
        return toCalendar(date).get(Calendar.MONTH);
    }

    /**
     * 获取第几周
     * @param date 时间
     * @return
     */
    public static int getWeek(Date date) {
        return toCalendar(date).get(Calendar.WEEK_OF_MONTH);
    }

    /**
     * 万年历
     * @param date
     * @return
     */
    public static Calendar toCalendar(Date date) {
        Calendar cal = Calendar.getInstance(Locale.getDefault(Locale.Category.FORMAT));
        cal.setFirstDayOfWeek(Calendar.WEEK_OF_MONTH);
        cal.setTime(date);
        return cal;
    }

    public static void main(String[] args) {

        String monthNoAndWeekNo = getMonthNoAndWeekNo(LocalDateTime.now());
        System.out.println("weekNoOfMonth :" + monthNoAndWeekNo);

        String monthNoAndWeekNo1 = getMonthNoAndWeekNo(LocalDate.now());
        System.out.println("weekNoOfMonth1 :" + monthNoAndWeekNo1);

        String monthNoAndWeekNo2 = getMonthNoAndWeekNo(new Date());
        System.out.println("weekNoOfMonth2 :" + monthNoAndWeekNo2);
    }


}

在这里插入图片描述

你可能感兴趣的:(Java获取时间几月第几周)