How Can I Find Saturdays And Sundays In A Given Month?
Solution 1:
The simplest way is to just iterate over all the days in the month, and check the day of week for each of them. For example:
// This takes a 1-based month, e.g. January=1. If you want to use a 0-based// month, remove the "- 1" later on.publicintcountWeekendDays(int year, int month) {
Calendar calendar = Calendar.getInstance();
// Note that month is 0-based in calendar, bizarrely.
calendar.set(year, month - 1, 1);
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
int count = 0;
for (int day = 1; day <= daysInMonth; day++) {
calendar.set(year, month - 1, day);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.SUNDAY || dayOfweek == Calendar.SATURDAY) {
count++;
// Or do whatever you need to with the result.
}
}
return count;
}
I'm absolutely sure there are far more efficient ways of doing this - but that's what I'd start with, and optimize when I'd found it's too slow.
Note that if you're able to use Joda Time that would make your life a lot easier...
Solution 2:
Try this:
import java.util.Calendar;
import java.util.GregorianCalendar;
publicclassSundays {
publicstaticvoidmain(String[] args) {
intyear=2012;
// put the month you wantintmonth= Calendar.JANUARY;
Calendarcal=newGregorianCalendar(year, month, 1);
do {
intday= cal.get(Calendar.DAY_OF_WEEK);
if (day == Calendar.SATURDAY || day == Calendar.SUNDAY) {
System.out.println(cal.get(Calendar.DAY_OF_MONTH));
}
cal.add(Calendar.DAY_OF_YEAR, 1);
} while (cal.get(Calendar.MONTH) == month);
}
}
Solution 3:
Base on the previous answer, I have a small modification When u find the first Saturday and Sunday, you can simply add 7 days to it until the month is changed.
Solution 4:
The java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API.
Also, quoted below is a notice at the Home Page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time
, the modern Date-Time API:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.temporal.TemporalAdjusters;
import java.util.List;
import java.util.stream.Collectors;
publicclassMain {
publicstaticvoidmain(String[] args) {
// Test
System.out.println(getWeekends(2));// All weekends of Feb in the current year
System.out.println(getWeekends(2020, 2));// All weekends of Feb 2020
}
/*
* All weekends (Sat & Sun) of the given month in the current year
*/static List<LocalDate> getWeekends(int month) {
LocalDatefirstDateOfTheMonth= LocalDate.now().withMonth(month).with(TemporalAdjusters.firstDayOfMonth());
return firstDateOfTheMonth
.datesUntil(firstDateOfTheMonth.plusMonths(1))
.filter(date -> date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY)
.collect(Collectors.toList());
}
/*
* All weekends (Sat & Sun) of the given year and the month
*/static List<LocalDate> getWeekends(int year, int month) {
LocalDatefirstDateOfTheMonth= YearMonth.of(year, month).atDay(1);
return firstDateOfTheMonth
.datesUntil(firstDateOfTheMonth.plusMonths(1))
.filter(date -> date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY)
.collect(Collectors.toList());
}
}
Output:
[2021-02-06, 2021-02-07, 2021-02-13, 2021-02-14, 2021-02-20, 2021-02-21, 2021-02-27, 2021-02-28]
[2020-02-01, 2020-02-02, 2020-02-08, 2020-02-09, 2020-02-15, 2020-02-16, 2020-02-22, 2020-02-23, 2020-02-29]
Non-Stream
solution:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;
publicclassMain {
publicstaticvoidmain(String[] args) {
// Test
System.out.println(getWeekends(2));// All weekends of Feb in the current year
System.out.println(getWeekends(2020, 2));// All weekends of Feb 2020
}
/*
* All weekends (Sat & Sun) of the given month in the current year
*/static List<LocalDate> getWeekends(int month) {
LocalDatefirstDateOfTheMonth= LocalDate.now().withMonth(month).with(TemporalAdjusters.firstDayOfMonth());
List<LocalDate> list = newArrayList<>();
for (LocalDatedate= firstDateOfTheMonth; !date
.isAfter(firstDateOfTheMonth.with(TemporalAdjusters.lastDayOfMonth())); date = date.plusDays(1))
if (date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY)
list.add(date);
return list;
}
/*
* All weekends (Sat & Sun) of the given year and the month
*/static List<LocalDate> getWeekends(int year, int month) {
LocalDatefirstDateOfTheMonth= YearMonth.of(year, month).atDay(1);
List<LocalDate> list = newArrayList<>();
for (LocalDatedate= firstDateOfTheMonth; !date
.isAfter(firstDateOfTheMonth.with(TemporalAdjusters.lastDayOfMonth())); date = date.plusDays(1))
if (date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY)
list.add(date);
return list;
}
}
Learn more about the modern Date-Time API from Trail: Date Time.
Solution 5:
Please go through this method, I faced a lot finally I created my own.
publicstaticintgetDayDiff(String dateFrom, String dateTo){ // DD/MM/YYYYTimestamptDtF= getTimestampDDmmYYYY(dateFrom);//returning timestamp from / DD/MM/YYYYTimestamptDtT= getTimestampDDmmYYYY(dateTo);
CalendardtF=newGregorianCalendar();
CalendardtT=newGregorianCalendar();
dtF.setTimeInMillis(tDtF.getTime());
dtT.setTimeInMillis(tDtT.getTime());
intcount=0;
while(dtF.before(dtT)){
count++;
dtF.add(Calendar.DAY_OF_YEAR, 1);
}
return count;
}
publicstaticintcountDateSatOrSun(String dateFrom, String dateTo){//DD/MM/YYYYTimestamptDtF= getTimestampDDmmYYYY(dateFrom);//returning timestamp from / DD/MM/YYYYTimestamptDtT= getTimestampDDmmYYYY(dateTo);
CalendardtF=newGregorianCalendar();
CalendardtT=newGregorianCalendar();
dtF.setTimeInMillis(tDtF.getTime());
dtT.setTimeInMillis(tDtT.getTime());
intcount=0;
while(dtF.before(dtT)){
if((dtF.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY| dtF.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY))
count++;
dtF.add(Calendar.DAY_OF_YEAR, 1);
}
return count;
}
It will give you exact result.
Post a Comment for "How Can I Find Saturdays And Sundays In A Given Month?"