Calculate number of weekdays between two dates in Java
public static int getWorkingDaysBetweenTwoDates(Date startDate, Date endDate) {
Calendar startCal = Calendar.getInstance();
startCal.setTime(startDate);
Calendar endCal = Calendar.getInstance();
endCal.setTime(endDate);
int workDays = 0;
//Return 0 if start and end are the same
if (startCal.getTimeInMillis() == endCal.getTimeInMillis()) {
return 0;
}
if (startCal.getTimeInMillis() > endCal.getTimeInMillis()) {
startCal.setTime(endDate);
endCal.setTime(startDate);
}
do {
//excluding start date
startCal.add(Calendar.DAY_OF_MONTH, 1);
if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
++workDays;
}
} while (startCal.getTimeInMillis() < endCal.getTimeInMillis()); //excluding end date
return workDays;
}
Start date and end date are exclusive, Only the days between given
dates will be counted. Start date and end date will not be included.
Calculate number of business days between two dates
Here's an answer implemented in Java 8 using java.time.*
.
public class TestSo47314277 {
/**
* A set of federal holidays. Compared to iteration, using a
* hash-based container provides a faster access for reading
* element via hash code. Using {@link Set} avoids duplicates.
* <p>
* Add more dates if needed.
*/
private static final Set<LocalDate> HOLIDAYS;
static {
List<LocalDate> dates = Arrays.asList(
LocalDate.of(2017, 1, 2),
LocalDate.of(2017, 1, 16),
LocalDate.of(2017, 2, 20),
LocalDate.of(2017, 5, 29),
LocalDate.of(2017, 7, 4),
LocalDate.of(2017, 9, 4),
LocalDate.of(2017, 10, 9),
LocalDate.of(2017, 11, 10),
LocalDate.of(2017, 11, 23),
LocalDate.of(2017, 12, 25)
);
HOLIDAYS = Collections.unmodifiableSet(new HashSet<>(dates));
}
public int getBusinessDays(LocalDate startInclusive, LocalDate endExclusive) {
if (startInclusive.isAfter(endExclusive)) {
String msg = "Start date " + startInclusive
+ " must be earlier than end date " + endExclusive;
throw new IllegalArgumentException(msg);
}
int businessDays = 0;
LocalDate d = startInclusive;
while (d.isBefore(endExclusive)) {
DayOfWeek dw = d.getDayOfWeek();
if (!HOLIDAYS.contains(d)
&& dw != DayOfWeek.SATURDAY
&& dw != DayOfWeek.SUNDAY) {
businessDays++;
}
d = d.plusDays(1);
}
return businessDays;
}
}
how to calculate number of days between two dates excluding weekend java
This will work for you
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = df.parse("10/08/2013");
Date date2 = df.parse("21/08/2013");
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
int numberOfDays = 0;
while (cal1.before(cal2)) {
if ((Calendar.SATURDAY != cal1.get(Calendar.DAY_OF_WEEK))
&&(Calendar.SUNDAY != cal1.get(Calendar.DAY_OF_WEEK))) {
numberOfDays++;
}
cal1.add(Calendar.DATE,1);
}
System.out.println(numberOfDays);
Live Demo
Out put
7
Calculating workday difference between two calendar dates
I highly recommend using the java.time.LocalDate::datesUntil
method found in Java 9 and later. It only takes a couple lines to calculate, rather than having to use Calendar
:
var startDate = LocalDate.parse("2018-03-08");
var endDate = LocalDate.parse("2018-04-22");
var numWeekDays = startDate.datesUntil(endDate)
.map(LocalDate::getDayOfWeek)
.filter(d -> d != DayOfWeek.SATURDAY && d != DayOfWeek.SUNDAY)
.count();
System.out.println(numWeekDays);
Output:
32
How can I count the number of weekdays between two dates, considering Saturday a weekday?
You can use sas function intck to find required interval. in your example, following will be the statement:
data want;
set testing_weekdays;
wkdays=intck('WEEKDAY1W',date_1,dat2_2);
run;
You can use different formats for Weekday interval. The days are numbered as Sunday(1) .. Saturday(7). So if you want to keep Sunday as a weekend, then WEEKDAY1W is used as interval.. Say if you want Monday(2), Wed(4) as weekends, then use- WEEKDAY24W
Calculate number of hours between two dates not including weekends
I find it cleaner with java.util.Calendar, here is an example getting number of hours since March 1st (8am) until current time :
final Calendar first = new Calendar.Builder()
.setDate(2016, 2, 1).set(Calendar.AM_PM, 0).set(Calendar.HOUR, 8).build();
final Calendar second = Calendar.getInstance();
int numberOfDays = 0;
long numberOfHours = 0;
//Get number of full days
while(first.get(Calendar.DATE) != second.get(Calendar.DATE)){
if(Calendar.SATURDAY != first.get(Calendar.DAY_OF_WEEK)
&& Calendar.SUNDAY != first.get(Calendar.DAY_OF_WEEK)){
numberOfDays++;
}
first.roll(Calendar.DATE, true);
}
//Get number of hours in the remaining day
numberOfHours = TimeUnit.MILLISECONDS
.toHours(second.getTimeInMillis() - first.getTimeInMillis());
System.out.println("Difference = " +
( numberOfDays * 24 + numberOfHours ) + " hour(s)");
How to calculate the working(excluding weekends) days in between two different dates in JAVA?
You have mistake in creating SimpleDateFormat
, change to yy
instead of yyyy
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");
This should solve your problems. I do not see any issues in your logic.
EDIT
As per your comments, if your start date is greater than end date then you have to swap it before while
loop
if(start.after(end)) {
Calendar tempCal;
tempCal = start;
start = end;
end = tempCal;
}
Related Topics
How to Achieve Javafx Mouse Event "Push and Hold"
Installing Oracle Jdk on Windows Subsystem for Linux
Linux Command for Extracting War File
How to Debug Java -Jni Using Gdb on Linux
How to Get Rjava 0.9-3 to Work on Os X 10.7.4 with Oracle Java 1.7
Ruby and Duck Typing: Design by Contract Impossible
Jsp, Can It Work Similar to Yield, Layout, Content_For in Ruby/Rails/Erb
How to Click an Element in Selenium Webdriver Using JavaScript
Differences Between System.Out.Println() and Return in Java
Java.Lang.Classnotfoundexception in Spite of Using Classpath Environment Variable
Inputstream.Available() Is 0 Always
What Do I Use Now That Handler() Is Deprecated
Getting Noclassdeffounderror When Using Common.Lang.Stringutils in Android Java Code
How to Add and Remove Elements of Enumeration at Runtime in Java