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 {


    /**
     * 根據(jù)時間獲取月的第幾周
     * @param sourceTime
     * @return
     */
    public static String getMonthNoAndWeekNo(LocalDateTime sourceTime) {
        Date date = Date.from(sourceTime.atZone(ZoneId.systemDefault()).toInstant());
        return join(date);
    }

    /**
     * 根據(jù)時間獲取月的第幾周
     * @param sourceTime
     * @return
     */
    public static String getMonthNoAndWeekNo(LocalDate sourceTime) {
        Date date = Date.from(sourceTime.atStartOfDay(ZoneOffset.ofHours(8)).toInstant());
        return join(date);
    }

    /**
     * 根據(jù)時間獲取月的第幾周
     * @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);
    }


}

在這里插入圖片描述
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容