根據(jù)業(yè)務(wù)需要獲取指定的月份區(qū)間拳芙,每月底有一個(gè)觸發(fā)時(shí)間點(diǎn)添怔,需要獲取到該時(shí)間點(diǎn)前一周的周日作為結(jié)束時(shí)間,而開(kāi)始時(shí)間則以上一個(gè)月的相同時(shí)間點(diǎn)所在周的周一做為開(kāi)始時(shí)間蚓曼。
代碼如下:
LocalDate localDate = LocalDate.now();
System.out.println("當(dāng)前時(shí)間:"+localDate);
LocalDate firstDayOfMonth = localDate.with(TemporalAdjusters.firstDayOfMonth());
LocalDate firstDayMonth = firstDayOfMonth.with(DayOfWeek.MONDAY);
System.out.println("每月1號(hào)的周所在周的周一:"+firstDayMonth);
LocalDate firstDay = localDate.with(DayOfWeek.MONDAY);
System.out.println("當(dāng)前周周一:"+firstDay+" 00:00:00");
LocalDate firstMonday = localDate.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));
System.out.println("當(dāng)前月第一周周一:"+firstMonday+" 00:00:00");
LocalDate lastSunday = localDate.with(TemporalAdjusters.lastInMonth(DayOfWeek.SUNDAY));
System.out.println("當(dāng)前月最后一個(gè)周日:"+lastSunday+" 23:59:59");
LocalDate May=localDate.minusMonths(1);
LocalDate April=localDate.minusMonths(2);
LocalDate March=localDate.minusMonths(3);
LocalDate Feb=localDate.minusMonths(4);
LocalDate Jan=localDate.minusMonths(5);
System.out.println("五月:"+May+" 四月:"+April+" 三月:"+March+" 二月:"+Feb+" 一月:"+Jan);
// 獲取上個(gè)月的最后一個(gè)周三所在周的周一 -- 開(kāi)始時(shí)間
// 獲取上一個(gè)月
LocalDate lastMonth = localDate.minusMonths(1);
System.out.println("前一個(gè)月的最后一天:"+lastMonth);
LocalDate lastMonthofLastWednsday = lastMonth.with(TemporalAdjusters.lastInMonth(DayOfWeek.WEDNESDAY));
System.out.println("前一個(gè)月最后一個(gè)周三:"+lastSunday+" 23:59:59");
LocalDate lastMonthOfMonday = lastMonthofLastWednsday.with(TemporalAdjusters.previous(DayOfWeek.MONDAY)).plusDays(1);
LocalDate lastMonthOdMondayNew = lastMonthofLastWednsday.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
System.out.println("前一個(gè)月最后一個(gè)周三的周一:"+lastMonthOfMonday+","+lastMonthOdMondayNew);
// 當(dāng)前月的最后一個(gè)周三所在周的上周的周日 --結(jié)束時(shí)間
LocalDate lastWednsday = localDate.with(TemporalAdjusters.lastInMonth(DayOfWeek.WEDNESDAY));
System.out.println("當(dāng)前月最后一個(gè)周三:"+lastWednsday+" 23:59:59");
// 最后一個(gè)周三的上一周的周三
LocalDate lastSecondWednsday = lastWednsday.minusDays(7);
System.out.println("當(dāng)月最后一個(gè)周三的上周三:"+lastSecondWednsday);
LocalDate lastSecondSunday = lastSecondWednsday.with(TemporalAdjusters.next(DayOfWeek.SUNDAY)).minusDays(1);
LocalDate lastSecondSundayNew = lastSecondWednsday.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
System.out.println("當(dāng)前月最后一個(gè)周三的上周日:"+lastSecondSunday+","+lastSecondSundayNew);
LocalDate lastWednsdayOfMonday = lastWednsday.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
System.out.println("當(dāng)前月最后一個(gè)周三所在周的周一:"+lastWednsdayOfMonday);
LocalDate wednsday = localDate.with(DayOfWeek.WEDNESDAY);
if(localDate.equals(wednsday)) {
System.out.println("同一天绩聘!");
}
運(yùn)行結(jié)果如下:
運(yùn)行結(jié)果
糾正:
lastMonthOfMonday 獲取的日期并非是當(dāng)前時(shí)間前一個(gè)月最后一個(gè)周三的周一
lastSecondSunday 獲取的日期也并非是當(dāng)前時(shí)間的最后一個(gè)周三的上周日