Java - Count Number of days except Holidays(Saturday and Sunday) [duplicate] - java

This question already has an answer here:
Calculate business days in java without saturdays, sunday and public holiday
(1 answer)
Closed 4 years ago.
I need to count for number of days except holidays(Saturday and sunday). For example my start date is 07/02/2018 and end date is 15/02/2018 (in dd/MM/yyyy format). I need to count number of working days between them. Can some please help me out? This is my code:
SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy");
//Date date12 = dateformat3.parse("17/07/1989");
String date1 = "11/07/2018";
String date2 = "20/07/2018";
// Date date2 = dateformat3.parse("15/10/2007");
Calendar startdate = Calendar.getInstance();
startdate.setTime(dateformat3.parse(date1));
Calendar enddate = Calendar.getInstance();
enddate.setTime(dateformat3.parse(date2));
while (!startdate.after(enddate)) {
int day = startdate.get(Calendar.DAY_OF_WEEK);
if ((day != Calendar.SATURDAY) && (day != Calendar.SUNDAY)) {
workingDays++;
}
}
I've tried with this code but is not showing any result.

You were close, just need to increment start date inside while loop.
public static void main(String[] args) throws Exception {
System.out.println(countDays("07/02/2018", "15/02/2018"));
}
public static int countDays(String startDate, String endDate) throws Exception {
int workingDays = 0;
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar startdate = Calendar.getInstance();
startdate.setTime(sdf.parse(startDate));
Calendar enddate = Calendar.getInstance();
enddate.setTime(sdf.parse(endDate));
while (!startdate.after(enddate)) {
int day = startdate.get(Calendar.DAY_OF_WEEK);
System.out.println(day);
if ((day != Calendar.SATURDAY) && (day != Calendar.SUNDAY)) {
workingDays++;
}
// increment start date, otherwise while will give infinite loop
startdate.add(Calendar.DATE, 1);
}
return workingDays;
}
As you can see, the only difference with the code I provided from yours (besides removing hard-coded values) is startdate.add(Calendar.DATE, 1);

I think you are doing wrong with your while condition.
Try this
while (ChronoUnit.DAYS.between(startdate.toInstant(), enddate.toInstant()) > 0) {
startdate.add(Calendar.DAY_OF_MONTH, 1);
if (startdate.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && startdate.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
workingDays++;
}
}

If you are using Java 8 you can use :
//Here I change the format of date to make it parsable
String date1 = "2018-07-11";
String date2 = "2018-07-20";
//Parse the date to LocalDate
LocalDate start = LocalDate.parse(date1);
LocalDate end = LocalDate.parse(date2);
//iterate over the list of dates between start and end date,
//then filter only those who are not equal SATURDAY or SUNDAY, then count the result
long result = Stream.iterate(start, date -> date.plusDays(1))
.limit(ChronoUnit.DAYS.between(start, end))
.filter(date -> date.getDayOfWeek() != DayOfWeek.SATURDAY
&& date.getDayOfWeek() != DayOfWeek.SUNDAY
).count();
In your case it will return 7 days

Related

How to generate list of dates taking into consideration the month of startDate and endDate when they fall in different month?

Assuming i have startDate, endDate,currentDate
1. I want to ignore instance where startDate and endDate fall outside of currentDate month.
2. When startDate and currentDate are of the same month but endDate has a month greater than currentDate, then create a list between startDate to end day of startDates month.
3. When endDate is of the same month as currentDate and startDate is less than currentDate month, then create a list between endDate and first day of currentDate
I would like some help with a method to handle this.
Thank You
First lets make a method that creates a sequence of dates given a start and stop date. This method makes use of plusDays in LocalDate to generate dates in a while loop.
public static List<LocalDate> makeDateInterval(LocalDate startDate, LocalDate endDate) {
List<LocalDate> list = new ArrayList<>();
if (startDate.isAfter(endDate)) {
return list;
}
LocalDate nextDate = startDate;
while (nextDate.isBefore(endDate)) {
list.add(nextDate);
nextDate = nextDate.plusDays(1);
}
list.add(endDate);
return list;
}
To sort out what the start and stop date is we need a simple logic to compare the months of the given dates and if we have a valid interval we call the above method
public static List<LocalDate> buildDateRange(LocalDate startDate, LocalDate endDate, LocalDate currentDate) {
LocalDate firstDate = null;
LocalDate secondDate = null;
if (startDate.getMonth() == currentDate.getMonth()) {
firstDate = startDate;
secondDate = currentDate;
}
if (endDate.getMonth() == currentDate.getMonth()) {
secondDate = endDate;
if (firstDate == null) {
firstDate = currentDate;
}
}
if (firstDate == null || secondDate == null) {
return new ArrayList<>(); //No valid interval, return empty list
}
return makeDateInterval(firstDate, secondDate);
}
A simple test today February 1st
public static void main(String[] args) {
LocalDate now = LocalDate.now();
LocalDate start = now.minusDays(5);
LocalDate end = now.plusDays(5);
System.out.println("Now: " + now + ", start: " + start + ", end: " +end);
List<LocalDate> list = buildDateRange(start, end, now);
for (LocalDate d : list) {
System.out.println(d);
}
}
generates the following output
Now: 2019-02-01, start: 2019-01-27, end: 2019-02-06
2019-02-01
2019-02-02
2019-02-03
2019-02-04
2019-02-05
2019-02-06

How to get saturday and sunday between two date in java [duplicate]

This question already has answers here:
Calculate number of weekdays between two dates in Java
(20 answers)
Closed 6 years ago.
StartDate: 2016-05-8 20:16:00;
EndDate: 2016-05-30 20:16:00;
public int saturdaysundaycount(Date d1, Date d2) {
Calendar c1 = Calendar.getInstance();
c1.setTime(d1);
Calendar c2 = Calendar.getInstance();
c2.setTime(d2);
int sundays = 0;
int saturday = 0;
while (c1.after(c2)) {
if (c2.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY || c2.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
sundays++;
saturday++;
c2.add(Calendar.DATE, 1);
c2.add(Calendar.DATE, 1);
}
System.out.println(sundays);
return saturday + sundays;
}
In this function I am trying to get total count of Saturdays and Sundays between two dates. But when I pass the date I get zero as a result. Please point out the mistake and suggest corrections.
It is not advisable to write full program but since you put effort, here is what seems to be working on my system and returning a value of 7.
public class CountWeekends {
public static void main(String[] args){
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
int count = 0;
try {
Date d1 = formatter.parse("2016-05-8 20:16:00");
Date d2 = formatter.parse("2016-05-30 20:16:00");
count = saturdaysundaycount(d1,d2);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Count of Sats & Sundays = "+count);
}
public static int saturdaysundaycount(Date d1, Date d2) {
Calendar c1 = Calendar.getInstance();
c1.setTime(d1);
Calendar c2 = Calendar.getInstance();
c2.setTime(d2);
int sundays = 0;
int saturday = 0;
while (! c1.after(c2)) {
if (c1.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY ){
saturday++;
}
if(c1.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY){
sundays++;
}
c1.add(Calendar.DATE, 1);
}
System.out.println("Saturday Count = "+saturday);
System.out.println("Sunday Count = "+sundays);
return saturday + sundays;
}
Logic: You need to keep increment start date by one day till it
surpasses end date and keep checking day on start date.
The problem is in your while, with this piece of code is working fine for me.
Check the endDate and startDate because I guess that you are sending it in the wrong order.
while (endDate.after(startDate)) {
if (endDate.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY ){
sundays++;
}else if (endDate.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY){
saturday++;
}
endDate.add(Calendar.DATE, -1);
}
Your code does not loop through the days. Please try the following code. In the while loop it loops through all the days between the given fist date and last date. It does this by adding a day to c1 in every iteration until c1 is after c2. This gives number of Saturdays and Sundays between given dates including those two days.
public static int saturdaysundaycount(Date d1, Date d2) {
Calendar c1 = Calendar.getInstance();
c1.setTime(d1);
Calendar c2 = Calendar.getInstance();
c2.setTime(d2);
int sundays = 0;
int saturdays = 0;
while (!c1.after(c2)) {
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd-E");
String formatted = format1.format(c1.getTime());
System.out.println("Current Date C1 : " + formatted);
if (c1.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
sundays++;
} else if (c1.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
saturdays++;
}
c1.add(Calendar.DATE, 1);
}
System.out.println("Sundays : " + sundays);
System.out.println("Saturdays : " + saturdays);
return saturdays + sundays;
}
public static int getNumberofSundays(String d1,String d2) throws Exception{ //object in Date form
Date date1=getDate(d1);
Date date2=getDate(d2);
Calendar c1=Calendar.getInstance();
c1.setTime(date1);
Calendar c2=Calendar.getInstance();
c2.setTime(date2);
int sundays=0;
while(c1.after(c2)){
if(c2.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY){
sundays++;
c2.add(Calendar.DATE,1);
}
}
System.out.println("number of days between 2 dates"+sundays);
return sundays;
}

How can i check that 2 dates between period(month)

i have 2 Date (start_date, end_date) with yyyy-MM-dd format and i want to check that if the month between in december 01 - march 31 then do something. For example my start_date is 2015-12-01 or 2016-02-01 and end_date 2016-02-12 then write something.
I have this
public void meethod(){
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = null;
Date endDate = null;
try {
startDate = df.parse(tf_start_date.getText());
endDate = df.parse(tf_end_date.getText());
} catch (ParseException e) {
e.printStackTrace();
}
if( /* what goes here? */ ) {
System.out.println("its between december-march");
} else {
}
}
tf_start_date and tf_end_date is a TextField and the value of TextFields like 2015-02-03
First, you should probably be using Calendar rather than Date. First, you'll need to construct the Calendar using a Calendar.Builder:
Calendar startCal = Calendar.Builder().setInstant(startDate);
Calendar endCal = Calendar.Builder().setInstant(endDate);
Then you can just check their months to see if they are one of the months you're looking for:
int startMonth = startCal.get(Calendar.MONTH);
if (startMonth == Calendar.DECEMBER ||
startMonth == Calendar.JANUARY ||
startMonth == Calendar.FEBRUARY ||
startMonth == Calendar.MARCH)
Similarly with endMonth.

How to calculate a full days difference between two dates considering daylight savings in java

I need to get the full days between two dates in java (the dates are given in Date type) .
For example:
01/01/2015/12:00:00 - 01/02/2015/11:59:00 isn't a full day
and i need to consider daylight savings.
I know that jodatime lib does that but i reached the 65k method limit and i cant use jodatime lib.
i tried the millisecond diff way and the while loop that uses the "before" method:
Android/Java - Date Difference in days
I manage to figure it out:
i used some of this code - https://stackoverflow.com/a/28865648/3873513
and added some of mine:
public static int calcDaysDiff(Date day1, Date day2) {
Date d1 = new Date(day1.getTime());
Date d2 = new Date(day2.getTime());
Calendar date1 = Calendar.getInstance();
date1.setTime(d1);
Calendar date2 = Calendar.getInstance();
date2.setTime(d2);
//checks if the start date is later then the end date - gives 0 if it is
if (date1.get(Calendar.YEAR) >= date2.get(Calendar.YEAR)) {
if (date1.get(Calendar.DAY_OF_YEAR) >= date2.get(Calendar.DAY_OF_YEAR)) {
return 0;
}
}
//checks if there is a daylight saving change between the two dates
int offset = calcOffset(d1, d2);
if (date1.get(Calendar.YEAR) > date2.get(Calendar.YEAR)) {
//swap them
Calendar temp = date1;
date1 = date2;
date2 = temp;
}
return calcDaysDiffAux(date1, date2) + checkFullDay(date1, date2, offset);
}
// check if there is a 24 hour diff between the 2 dates including the daylight saving offset
public static int checkFullDay(Calendar day1, Calendar day2, int offset) {
if (day1.get(Calendar.HOUR_OF_DAY) <= day2.get(Calendar.HOUR_OF_DAY) + offset) {
return 0;
}
return -1;
}
// find the number of days between the 2 dates. check only the dates and not the hours
public static int calcDaysDiffAux(final Calendar day1, final Calendar day2) {
Calendar dayOne = (Calendar) day1.clone(),
dayTwo = (Calendar) day2.clone();
if (dayOne.get(Calendar.YEAR) == dayTwo.get(Calendar.YEAR)) {
return Math.abs(dayOne.get(Calendar.DAY_OF_YEAR) - dayTwo.get(Calendar.DAY_OF_YEAR));
} else {
int extraDays = 0;
while (dayTwo.get(Calendar.YEAR) > dayOne.get(Calendar.YEAR)) {
dayTwo.add(Calendar.YEAR, -1);
// getActualMaximum() important for leap years
extraDays += dayTwo.getActualMaximum(Calendar.DAY_OF_YEAR);
}
return extraDays - day1.get(Calendar.DAY_OF_YEAR) + day2.get(Calendar.DAY_OF_YEAR);
}
}
public class DateDiff {
public static void main(String[] av) {
SimpleDateFormat myFormat = new SimpleDateFormat("MM/dd/yyyy/HH:mm:ss");
String inputString1 = "01/01/2015/12:00:00";
String inputString2 = "01/02/2015/11:59:00";
try {
Date date1 = myFormat.parse(inputString1);
Date date2 = myFormat.parse(inputString2);
long diff = date2.getTime() - date1.getTime(); // Calculate the different
int days = (int) (diff / (1000*60*60*24)); // This convert milliseconds to days
System.out.println ("Days differ: " + days);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The following code will calculate the two dates given, the result print is:
Days differ: 0

How to compare two date and time in android

I have one problem is there. How to compare 2 date and time
enter code here
if(fromdate<=nowdt.now() && todate>= nowdt.now()){
////
}
The java.util.Date object contains methods .before(), .after and .equals() for comparing dates.
if((fromdate.before(nowDt) || fromDate.equals(nowDt))
&& ((todate.after(nowDt) || toDate.equals(nowDt))
////
}
A function to compare two date and time:
public static int compareTwoDates(Date date1, Date date2) {
if (date1 != null && date2 != null) {
int retVal = date1.compareTo(date2);
if (retVal > 0)
return 1; // date1 is greatet than date2
else if (retVal == 0) // both dates r equal
return 0;
}
return -1; // date1 is less than date2
}
You can use it where you want to. Result will be > 0 if date1 > date2, = 0 if date1 = date2, < 0 if date1 < date2. Hope it helps.
- Use Joda Time library to do this....
Eg:
Date ds = new Date();
DateTime d = new DateTime(ds);
DateTime e = new DateTime(2012,12,07, 0, 0);
System.out.println(d.isEqual(e));
System.out.println(d.toDateMidnight().isEqual(e.toDateMidnight()));
///////////////////////////// OR
System.out.println(d.withTimeAtStartOfDay().isEqual(e.withTimeAtStartOfDay()));
Try this one out to find time difference
Calendar Day = Calendar.getInstance();
Day.set(Calendar.DAY_OF_MONTH,25);
Day.set(Calendar.MONTH,7);
Day.set(Calendar.YEAR, 1985);
Calendar today = Calendar.getInstance();
long diff = today.getTimeInMillis() - Day.getTimeInMillis();
You can write
long nowTime = System.currentTimeMillis();
if(fromdate.getTime() <= nowTime && nowTime <= todate.getTime()) {
or you can write
Date nowDate = new Date();
if(fromdate.compareTo(nowDate) * nowDate.compareTo(todate) >= 0) {
or
if(!fromdate.after(nowDate) && !todate.before(nowDate))
use this answer
if((options.FromDate.before(now_Date)||options.FromDate.equals(now_Date)) && (options.ToDate.after(now_Date)|| options.ToDt.equals(now_Date)) ){
do some processs........
}

Categories

Resources