I want to find number of weekend (here weekend may be one or more day) from a particular month of particular date. Like if number of weekend is 2 i.e. saturday and sunday than how to calculate total number of weekend from a date like 2019-11-15 in java.
Asked
Active
Viewed 385 times
-2
-
Could you explain that a little more in detail? What if the first day of a month is a Sunday, does that count as weekend number one for that month? – deHaar Nov 15 '19 at 07:32
-
1Have you tried anything? – Gaurav Jeswani Nov 15 '19 at 07:32
-
this will help you https://stackoverflow.com/questions/3272454/in-java-get-all-weekend-dates-in-a-given-month – Nov 15 '19 at 07:38
-
You are expected to do research prior asking a question. It also works much better to include your own efforts, instead of simply dumping your requirements here, looking to others to do all the heavy lifting on your behalf. – GhostCat Nov 15 '19 at 07:39
-
@GhostCatsaysReinstateMonica why would anyone upvote this question? It doesn't even make sense. – xenteros Nov 15 '19 at 07:41
-
@xenteros Honestly, I don't know. Probably the person writing the code-only answer helped with that, to get the OP to upvote levels. I for sure didn't upvote. – GhostCat Nov 15 '19 at 07:56
-
You will want to look into `LocalDate` and `DayOfWeek` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). Under the linked original question I recommend the [answer by Ortomala Lokni](https://stackoverflow.com/a/30845918/5772882) and [by Basil Bourque](https://stackoverflow.com/a/39925397/5772882). – Ole V.V. Nov 15 '19 at 17:19
1 Answers
-1
public int weekendCount(int year, int month) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, 1);
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
int cnt = 0;
for (int i= 1; i<= daysInMonth; i++) {
calendar.set(year, month - 1, i);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.SUNDAY || dayOfWeek == Calendar.SATURDAY) {
cnt++;
}
}
return cnt;
}
Try this.
year -2019, month -11 output=9

Gaurav Dhiman
- 953
- 6
- 11