How to make a list of all calendar dates in 2009 and 2010 that fall from Monday to Thursday?

I need to loop back and make a list of all calendar dates in 2009 and 2010 that fall on Monday - Thursday of each week and write them down as a map of rows for a day-month matched with the day of the week:

"19-10-2010", "Tuesday"
"4-10-2010", "Monday"

Is there a Java library that can help with this, or can only be done using the standard library?

+3
source share
2 answers

Use Calendar:

  • Install YEARbefore 2009
  • Set DAY_OF_YEARto 1
  • Iterations all days in 2009, 2010, Mon-Thu validation.

the code:

Calendar cal = Calendar.getInstance();

// Start in 1 Jan 2009
cal.set(YEAR, 2009);
cal.set(DAY_OF_YEAR, 1);

// Iterate while in 2009 or 2010
while (cal.get(YEAR) <= 2010)
{
    int dow = cal.get(DAY_OF_WEEK);
    if (dow >= Calendar.MONDAY && dow <= Calendar.THURSDAY))
    {
        // add to your map
    }
    cal.add(Calendar.DATE, 1);
}

Update:

, Fri, Sat, Sun: 4 , , 1 :

while (cal.get(YEAR) <= 2010)
{
    int dow = cal.get(DAY_OF_WEEK);
    if (dow >= Calendar.MONDAY && dow <= Calendar.THURSDAY))
    {
        // add to your map
    }
    cal.add(Calendar.DATE, (dow == Calendar.THURSDAY)? 4 : 1);
}
+3

guava. .

    ConcurrentMap<String, String> m = new MapMaker()
            .makeComputingMap(new Function<String, String>() {
                Calendar cal = Calendar.getInstance();
                SimpleDateFormat formatDay = new SimpleDateFormat("EEEE");
                SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
                final String notApplicable = "NA";

                @Override
                public String apply(String arg0) {

                    try {
                        cal.setTime(format.parse(arg0));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    int dow = cal.get(DAY_OF_WEEK);
                    int year=cal.get(YEAR);
                    if(year!=2009&&year!=2010)
                        return notApplicable;
                    if (dow >= Calendar.MONDAY && dow <= Calendar.THURSDAY) {
                        return formatDay.format(cal.getTime());
                    }
                    return notApplicable;
                }
            });

, :

 m.get("01-01-2009");
0

Source: https://habr.com/ru/post/1770492/


All Articles