January four-week Java implementation method

Source: Internet
Author: User

Requirements: Given any one months, how to follow the Chinese week habit, one months into four time periods

(1) based on Natural week

(2) cannot cross-month

(3) to merge the natural week with less days to its nearest natural week

(4) The final result should be one months divided into four time periods, and give the start and end date of each paragraph

Probably the demand as described above, no nonsense, on the code: (in the package in the main () function, direct copy can, remember to guide the corresponding package and new entity Class)

 Public classOne_month_four_week { Public Static voidMain (string[] args) {    intYear = 2017; intmonth = 10;//change to the year you want, run to view results Calendar Cal=calendar.getinstance ();    Cal.set (Calendar.year, year); Cal.set (Calendar.month, MONTH-1);//-1 only correct    intDays = Cal.getactualmaximum (calendar.date);//Calendar.day_of_month also onSystem.out.println ("First, calculate this month has" + Days + "Day"); String[] Weekdays= {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};//The beginning of a week abroad    int[] Chinaweek = {7, 1, 2, 3, 4, 5, 6};//the day of the week that corresponds to ChinaSimpleDateFormat Str_date_format=NewSimpleDateFormat ("Yyyy-mm-dd"); List<EachDayAttr> MonthDay =NewArraylist<>(); intWeek_of_month = 1;  for(inti = 1; I <= days; i++) {eachdayattr oneday=Neweachdayattr ();        Oneday.setwhich (i); //calculate each day of the month, corresponding to the days of the weekString daystr = year + "-" + month + "-" +i; Date daysdate=NULL; Try{daysdate=Str_date_format.parse (DAYSTR); } Catch(ParseException e) {e.printstacktrace ();        } cal.settime (Daysdate); intW1 = Cal.get (Calendar.day_of_week)-1;//indicates the day of the week one        intWhich_day_chinaweek =CHINAWEEK[W1]; System.out.println ("The month of the first" + i + "Days, the Week (foreign habits) of the first" + W1 + "Days:" + weekdays[w1] + ">> corresponding to the Chinese week of the" + Which_day_chinaweek + "Day! "); //key: Each day of the month corresponds to the first week of the week in China        if(Which_day_chinaweek = = 1) {//Monday, the beginning of a new week in Chinese habitweek_of_month++;        Oneday.setweek (Week_of_month); } Else{Oneday.setweek (week_of_month);    } monthday.add (Oneday); }    //Group: GROUP by Chinese habitMap<integer, list<eachdayattr>> weekgroup =NewTreemap<>();  for(eachdayattr oneday:monthday) {if(Weekgroup.containskey (Oneday.getweek ())) {Weekgroup.get (Oneday.getweek ()). Add (Oneday); } Else{List<EachDayAttr> AddGroup =NewArraylist<>();        Addgroup.add (oneday);        Weekgroup.put (Oneday.getweek (), addgroup); }    }        //re-grouping: Merging into the surrounding    if(weekgroup.size () = = 4) {        //Weekgroup does not do the processing}Else if(weekgroup.size () = = 5) {        if(Weekgroup.get (1). Size () < Weekgroup.get (5). Size ()) {Weekgroup.get (2). AddAll (Weekgroup.get (1)); Weekgroup.remove (1); } Else{weekgroup.get (4). AddAll (Weekgroup.get (5)); Weekgroup.remove (5); }    } Else if(weekgroup.size () = = 6) {Weekgroup.get (2). AddAll (Weekgroup.get (1)); Weekgroup.get (5). AddAll (Weekgroup.get (6)); Weekgroup.remove (1); Weekgroup.remove (6); }    //The Weekgroup is sorted by days, whichever is the start date, the maximum is the end date .     for(Entry<integer, list<eachdayattr>>Entry:weekGroup.entrySet ()) {Collections.sort (Entry.getvalue (),NewComparator<eachdayattr>() {         Public intCompare (eachdayattr day1, eachdayattr day2) {returnDay1.getwhich ()-Day2.getwhich ();    }        }); }    //Finally, from the good group, the sequence of weekgroup in the value package//weekgroup-->entry is an integer, and the value is list<?> collectionMap<integer, string[]> Rtresult =NewHashmap<>(); intSignweek = 1;  for(Entry<integer, list<eachdayattr>>Entry:weekGroup.entrySet ()) {string[] Addresult=NewString[2]; intFirstDay = Entry.getvalue (). Get (0). Getwhich (); intLastday = Entry.getvalue (). Get (Entry.getvalue (). Size ()-1). Getwhich (); addresult[0] = year + "-" + month + "-" +FirstDay; addresult[1] = year + "-" + month + "-" +Lastday;        Rtresult.put (Signweek, Addresult); Signweek++; }    //at this point, the output looks at the results     for(Entry<integer, string[]>Entry:rtResult.entrySet ()) {System.out.println ("----the Month" + entry.getkey () + "Week-----"); System.out.println ("Start Date:" + entry.getvalue () [0]); System.out.println ("End Date:" + Entry.getvalue () [1]); }    }}

Summary: The above method. Involved in the knowledge point is actually a lot, is also a daily project encountered more, such as the calendar of the date of the class, as well as group sorting, map traversal;

In addition to the custom entity classes, OCD's small partners can look under:

 Public class eachdayattr {    privateint  which;         Private int Week;         Private int Flag;

Get and Set methods omitted}

At last. Attached SQL big God directly with SQL is how to one months according to China Week (here one months up to six weeks, in order to be clearer, I have changed, but the SQL essence unchanged)

Select min(DT) starts a week,Max(DT) At the end of the week,Count(flag) The number of Sunday, Row_number () Over(Order  by 1) asWeek number from (        Select  LevelRN, Trunc (To_date (201707,'yyyymm'),'mm')+  Level - 1DT,Max(Decode (To_char (Trunc (To_date (201707,'yyyymm'),'mm')+  Level - 1,'D'),2, Level,0)) Over(Order  by  Level) Flag fromDual Connect by  Level <=Last_day (Trunc (To_date (201707,'yyyymm')))-Trunc (To_date (201707,'yyyymm'),'mm')+ 1    )      Group  byFlagOrder  by min(RN)

This is implemented in the MyBatis, the parameters passed is the shaping of the year, such as int yyyymm = 201707;

January four-week Java implementation method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.