获取当前时间的前几个月的星期起始结束时间
Posted scode2
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获取当前时间的前几个月的星期起始结束时间相关的知识,希望对你有一定的参考价值。
每天学习一点点 编程PDF电子书、视频教程免费下载:
http://www.shitanlife.com/code
实现的效果打印出来如下:
第4月第1周----------2018-4-2===2018-4-8 第4月第2周----------2018-4-9===2018-4-15 第4月第3周----------2018-4-16===2018-4-22 第4月第4周----------2018-4-23===2018-4-29 第4月第5周----------2018-4-30===2018-5-6 第5月第1周----------2018-5-7===2018-5-13 第5月第2周----------2018-5-14===2018-5-20
工具类代码:
@Service public class ToolsService { /** * get Calendar of given year * @param year * @return */ private Calendar getCalendarFormYear(int year){ Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); cal.set(Calendar.YEAR, year); return cal; } /** * get start date of given week no of a year * @param year * @param weekNo * @return */ public String getStartDayOfWeekNo(int year,int weekNo){ Calendar cal = getCalendarFormYear(year); cal.set(Calendar.WEEK_OF_YEAR, weekNo); return cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DAY_OF_MONTH); } /** * get the end day of given week no of a year. * @param year * @param weekNo * @return */ public String getEndDayOfWeekNo(int year,int weekNo){ Calendar cal = getCalendarFormYear(year); cal.set(Calendar.WEEK_OF_YEAR, weekNo); cal.add(Calendar.DAY_OF_WEEK, 6); return cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DAY_OF_MONTH); } }
逻辑代码:
// 获取当前时间在今年的周数 Date todayDate = new Date(); Calendar calendar = Calendar.getInstance(); calendar.setFirstDayOfWeek(Calendar.MONDAY); calendar.setTime(todayDate); int currentWeekIndex = calendar.get(Calendar.WEEK_OF_YEAR); int currentMonthIndex = calendar.get(Calendar.MONTH)+1; int currentYear = calendar.get(Calendar.YEAR); int monthWeekCount = 1; int tempMonth = 0; for(int i=currentWeekIndex-10; i<currentWeekIndex; i++) { if(i<1) { continue; } String weekStartTime = toolsService.getStartDayOfWeekNo(currentYear, i); int startMonth = Integer.parseInt(weekStartTime.split("-")[1]); if(startMonth < currentMonthIndex - 1) { continue; } if(tempMonth != startMonth) { tempMonth = startMonth; monthWeekCount = 1; } String weekEndTime = toolsService.getEndDayOfWeekNo(currentYear, i); System.out.println("第" + startMonth + "月第" + monthWeekCount +"周----------" +weekStartTime + "===" + weekEndTime); monthWeekCount ++; }
每天学习一点点 编程PDF电子书、视频教程免费下载:
http://www.shitanlife.com/code
以上是关于获取当前时间的前几个月的星期起始结束时间的主要内容,如果未能解决你的问题,请参考以下文章