how to find total weekends between two dates in java
In this article we are going to learn about Date class in Java and also placed few of the examples to find total weekends between two dates and to find Saturday and Sunday's in the current year. In this article we are going to use Serializable, Cloneable and Comparable in Java. If you should have basic knowledge about these interfaces, good enough.
Date: Date class is part of java.util package. Which will specify the current date with Time. In other words, the Date class represents specific instant in time, with milliseconds precision. Date class inherits methods from the super class called Object. Internal declaration of Date class is as follows,
As per the above lines, Date class implements Serializable, Cloneable, Comparable interfaces on top of Java super class called Object. How to create Date object? Since, Date is a normal class, we can create object directly by using new operator in Java.
As on when we have created Date, it will give you the Date in above output format. But, to show Date to client in the above format will not be correct. To convert the above date into specific format we need to use SimpleDateFormat class. SimpleDateFormat class has two different methods format() for formatting into specific type and parse() for converting the String into Date. Most commonly seen Date formats in any of the application is like dd-MM-YYYY or dd-MMM-YYYY or YYYY-MM-dd or YYYY-MMM-dd.
Weekends in current year:
WeekendFinder class contains the logic to identify the weekends in current year. It will print with date of the weekend. Here, weekends are considered only Saturday and Sunday, for different Countries might have different weekends. This will work only Saturday and Sunday weekend Countries like India, US, UK..etc
No of weekends between two dates:
This is one of the real time scenario I have faced to find total weekends between the given range of dates. To provide a facility to enter input dates from UI, I have used JOptionPane. JOptionPane present under the package of javax.swing.
As on when you try to execute the above program, you will get a input popup of JOptionPane to fill Date in the format of dd-MM-YYYY like 01-01-2018.
Similary, you have to enter end date also in the same format still when you need to calculate weekends, like below.
Now, we will see the output as like below image in JOptionPane and print the console with each weekend with the specific date.
Date: Date class is part of java.util package. Which will specify the current date with Time. In other words, the Date class represents specific instant in time, with milliseconds precision. Date class inherits methods from the super class called Object. Internal declaration of Date class is as follows,
public class Date extends Object implements Serializable,Cloneable,Comparable<T>
As per the above lines, Date class implements Serializable, Cloneable, Comparable interfaces on top of Java super class called Object. How to create Date object? Since, Date is a normal class, we can create object directly by using new operator in Java.
new Date(); Output: Mon Jul 09 21:54:50 IST 2018
As on when we have created Date, it will give you the Date in above output format. But, to show Date to client in the above format will not be correct. To convert the above date into specific format we need to use SimpleDateFormat class. SimpleDateFormat class has two different methods format() for formatting into specific type and parse() for converting the String into Date. Most commonly seen Date formats in any of the application is like dd-MM-YYYY or dd-MMM-YYYY or YYYY-MM-dd or YYYY-MMM-dd.
package com.javatbrains.practice; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class DateTest { public static void main(String[] args) { try { SimpleDateFormat dateFormatter = new SimpleDateFormat(); Date serverdate = new Date(); //Below line prints the your computer date System.out.println("Server Date: = " + serverdate); final String currentDate = dateFormatter.format(serverdate); GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(dateFormatter.parse(currentDate)); calendar.add(Calendar.DAY_OF_MONTH, 0); Date enddate = calendar.getTime(); //Below line prints the Gregorian Calendar date System.out.println("Gregorian calender Date: " + enddate); if (null != serverdate) { //Converting Current date into yyyy-MM-dd format String currentDateString = new SimpleDateFormat("yyyy-MM-dd") .format(serverdate); System.out.println("Current Date in yyyy-MM-dd format: " + currentDateString); //Converting Current date into dd-MMM-yyyy format String endDateString = new SimpleDateFormat("dd-MMM-yyyy") .format(enddate); System.out.println("Current Date in dd-MMM-yyyy format: " + endDateString); //Showing the current Year only System.out.println("Current Year: " + calendar.get(Calendar.YEAR)); //temp_month get the month currentMonth-1 int temp_month = calendar.get(Calendar.MONTH); int month = temp_month + 1; System.out.println("Current Month: " + month); } /* * The below lines retrieves the year, month and day from date * object by using the normal Calendar */ //Creating the Calendar instance Calendar cal = Calendar.getInstance(); //setting current server time to Calendar cal.setTime(serverdate); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) + 1; int day = cal.get(Calendar.DAY_OF_MONTH); System.out.println("Year: " + year + " Month: " + month + " Day: " + day); } catch (Exception e) { System.out.println(e.getMessage()); } } } Output: Server Date: = Mon Jul 09 22:21:11 IST 2018 Gregorian calender Date: Mon Jul 09 22:21:00 IST 2018 Current Date in yyyy-MM-dd format: 2018-07-09 Current Date in dd-MMM-yyyy format: 09-Jul-2018 Current Year: 2018 Current Month: 7 Year: 2018 Month: 7 Day: 9
Weekends in current year:
WeekendFinder class contains the logic to identify the weekends in current year. It will print with date of the weekend. Here, weekends are considered only Saturday and Sunday, for different Countries might have different weekends. This will work only Saturday and Sunday weekend Countries like India, US, UK..etc
package com.javatbrains.practice; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; public class WeekendFinder { private Calendar cal = null; private int year = -1; private ArrayList<Date> weekendList = null; public WeekendFinder(int year) { this.year = year; cal = Calendar.getInstance(); try { // Sets the date to the 1st day of the 1st month of the specified // year cal.setTime(new SimpleDateFormat("dd/MM/yyyy").parse("01/01/" + this.year)); } catch (java.text.ParseException e) { System.err.println("Error parsing date: " + e.getMessage()); e.printStackTrace(); } weekendList = new ArrayList<Date>(53); } public void findWeekends() { // The while loop ensures that you are only checking dates in the // specified year while (cal.get(Calendar.YEAR) == this.year) { // The switch checks the day of the week for Saturdays and Sundays switch (cal.get(Calendar.DAY_OF_WEEK)) { case Calendar.SATURDAY: case Calendar.SUNDAY: weekendList.add(cal.getTime()); break; } // Increment the day of the year for the next iteration of the while // loop cal.add(Calendar.DAY_OF_YEAR, 1); } } // Convenience method which just displays the contents of the ArrayList to // the //console public void displayWeekends() { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); for (int i = 0; i < weekendList.size(); i++) { System.out.println("WEEKEND : " + sdf.format((Date) weekendList.get(i))); } } public static void main(String[] args) { // The program requires one argument of a year, so for example you could // run //the program with "java WeekendCalculator 2014" WeekendFinder wf = new WeekendFinder(Calendar.getInstance().get(Calendar.YEAR)); wf.findWeekends(); wf.displayWeekends(); } }
No of weekends between two dates:
This is one of the real time scenario I have faced to find total weekends between the given range of dates. To provide a facility to enter input dates from UI, I have used JOptionPane. JOptionPane present under the package of javax.swing.
package com.javatbrains.practice; import java.util.Calendar; import java.util.GregorianCalendar; import javax.swing.JOptionPane; public class CalculateWeekends { boolean debug = true; public static void main(String[] args) { CalculateWeekends calculateweekends = new CalculateWeekends(); calculateweekends.test(); } public void test() { String startDate = JOptionPane .showInputDialog("Please enter the start date as dd-MM-YYYY"); String endDate = JOptionPane .showInputDialog("Please enter the end date as dd-MM-YYYY"); if (debug) System.out.println("Your entering start date is: " + startDate); if (debug) System.out.println("Your entering end date is: " + endDate); if (checkDateString(startDate) && checkDateString(endDate)) { if (debug) System.out.println("Both dates are okay."); GregorianCalendar firstdate = getDate(startDate); GregorianCalendar seconddate = getDate(endDate); int number = countNumberOfSaturdaysAndSundays(firstdate, seconddate); if (debug) System.out.println("There are " + String.valueOf(number) + " Saturdays or Sundays between " + startDate + " and " + endDate); JOptionPane.showMessageDialog(null, "There are " + String.valueOf(number) + " Saturdays or Sundays between " + startDate + " and " + endDate); } else { if (debug && !checkDateString(startDate)) System.out.println("Debug: Problem with " + startDate); if (debug && !checkDateString(endDate)) System.out.println("Debug: Problem with " + startDate); } } public boolean checkDateString(String datestring) { boolean status = false; if ((datestring.indexOf("-") > 0) && (datestring.lastIndexOf("-") > datestring.indexOf("-"))) { int day = toInt(datestring.substring(0, datestring.indexOf("-"))); int month = toInt(datestring.substring(datestring.indexOf("-") + 1, datestring.lastIndexOf("-"))); int year = toInt(datestring .substring(datestring.lastIndexOf("-") + 1)); status = ((day > 0) && (month > 0) && (year > 0) && (day <= 31) && (month <= 12) && (String.valueOf(year).length() == 4)); } return status; } public GregorianCalendar getDate(String datestring) { int day = toInt(datestring.substring(0, datestring.indexOf("-"))); int month = toInt(datestring.substring(datestring.indexOf("-") + 1, datestring.lastIndexOf("-"))); int year = toInt(datestring.substring(datestring.lastIndexOf("-") + 1)); return new GregorianCalendar(year, month - 1, day); } private int toInt(String s) { int n = -1; try { n = Integer.parseInt(s); } catch (NumberFormatException nfe) { System.err.println("NumberFormatException: " + nfe.getMessage()); JOptionPane.showMessageDialog(null, s + "is in the incorrect date format.", "NumberFormatException", JOptionPane.ERROR_MESSAGE); } return n; } public int countNumberOfSaturdaysAndSundays(GregorianCalendar first, GregorianCalendar second) { int count = 0; Calendar currentcalendarday = first; Calendar lastcalendarday = second; while (!currentcalendarday.equals(lastcalendarday)) { if (isOnSaturday(currentcalendarday)) count++; if (isOnSunday(currentcalendarday)) count++; currentcalendarday.add(Calendar.DATE, 1); } return count; } public boolean isOnSaturday(Calendar calendardate) { if (debug) { if (calendardate.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) { System.out.println("Debug: " + String.valueOf(calendardate.get(Calendar.DATE)) + "-" + String.valueOf(calendardate.get(Calendar.MONTH) + 1) + "-" + String.valueOf(calendardate.get(Calendar.YEAR)) + " is a SATURDAY."); } else { System.out.println("Debug: " + String.valueOf(calendardate.get(Calendar.DATE)) + "-" + String.valueOf(calendardate.get(Calendar.MONTH) + 1) + "-" + String.valueOf(calendardate.get(Calendar.YEAR)) + " is not a SATURDAY."); } } return (calendardate.get(Calendar.DAY_OF_WEEK) == 1); } public boolean isOnSunday(Calendar calendardate) { if (debug) { if (calendardate.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { System.out.println("Debug: " + String.valueOf(calendardate.get(Calendar.DATE)) + "-" + String.valueOf(calendardate.get(Calendar.MONTH) + 1) + "-" + String.valueOf(calendardate.get(Calendar.YEAR)) + " is a SUNDAY."); } else { System.out.println("Debug: " + String.valueOf(calendardate.get(Calendar.DATE)) + "-" + String.valueOf(calendardate.get(Calendar.MONTH) + 1) + "-" + String.valueOf(calendardate.get(Calendar.YEAR)) + " is not a SUNDAY."); } } return (calendardate.get(Calendar.DAY_OF_WEEK) == 7); } }
As on when you try to execute the above program, you will get a input popup of JOptionPane to fill Date in the format of dd-MM-YYYY like 01-01-2018.
Similary, you have to enter end date also in the same format still when you need to calculate weekends, like below.
Now, we will see the output as like below image in JOptionPane and print the console with each weekend with the specific date.
Comments
Post a Comment