Although Java comes with the calendar class seems to be very useful, but as a small white I do not use. Friends say sometimes need to calculate any two dates that have a few Monday or Wednesday. Ask me if I can achieve, I think, can achieve, perhaps the code is not elegant. The specific code is placed below. Welcome friends to share with me better ideas or tools ~
PackageCn.example.mapper;Importjava.text.ParseException;ImportJava.text.SimpleDateFormat;ImportJava.util.Calendar;Importjava.util.Date; Public classDateutil { Public Static voidMain (string[] args) {Try{System.out.println ("with" + Getmondaynumber ("2017-02-03", "2017-02-16", 5) + "one"); } Catch(ParseException e) {e.printstacktrace (); } } /*** Days of the week during the inquiry day * date format YYYY-MM-DD yyyy-mm-dd 1-7 (for Monday to Sunday) *@paramstartday Start date of the prepared query *@paramEndday the end date of the prepared query *@paramThe day of the week that DayOfWeek ready to check (how many weeks are you looking for?) ) * @returncontains the number of days of the week checked *@throwsParseException does not support cross-year queries, does not support end dates earlier than the start date, weeks of input errors, etc.*/ Public Static intGetmondaynumber (String startday,string endday,intDayOfWeek)throwsparseexception{SimpleDateFormat SDF=NewSimpleDateFormat ("Yyyy-mm-dd"); intDifferenceday = 0; //Conversion Start DateDate StartDate =Sdf.parse (StartDay); //Conversion End DateDate endDate =Sdf.parse (Endday); //instantiating a start and end calendar ObjectCalendar Startcalendar =calendar.getinstance (); Calendar Endcalendar=calendar.getinstance (); //set the time of the Calendar object individuallyStartcalendar.settime (StartDate); Endcalendar.settime (endDate); //define the starting and ending dates for the first week of each intStartweek =Startcalendar.get (calendar.week_of_year); intEndweek =Endcalendar.get (calendar.week_of_year); //What day of the week is the starting date? intStartdayofweek =Startcalendar.get (Calendar.day_of_week); if(Startdayofweek = = 1) {Startdayofweek= 7; Startweek--; }Elsestartdayofweek--; //What is the day of the week? intEnddayofweek =Endcalendar.get (Calendar.day_of_week); if(Enddayofweek = = 1) {Enddayofweek= 7; Endweek--; }Elseenddayofweek--; //calculate the number of weeks between differences intDifferenceweek = Endweek-Startweek; //Start Calculation if(Startdayofweek <=DayOfWeek) { if(Enddayofweek >=dayOfWeek) Differenceday= Differenceweek + 1; }Else if(Startdayofweek >DayOfWeek) { if(Enddayofweek <dayOfWeek) Differenceday= DifferenceWeek-1; }Else{differenceday=Differenceweek; } returnDifferenceday; }}
Think there is no technical content, this record it, there is time to optimize under, for example, to cross-year query.
Java implementation calculation with several weeks in two dates