How to display all Mondays between two dates? - java

Im trying display all Mondays between two dates but I have no idea how to do it. I want ask user to input two dates using Scanner, to output all Mondays.
String s = "2020-07-20";
String e = "2020-09-20";
LocalDate start = LocalDate.parse(s);
LocalDate end = LocalDate.parse(e);
List<LocalDate> totalDates = new ArrayList<>();
while (!start.isAfter(end)) {
totalDates.add(start);
start = start.plusDays(1);
}

To get the the first Monday, use:
LocalDate monday = start.with(TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY));
Now you have to deal with an edge case: What if there is no Monday between start and end? That would mean that the Monday computed here is after end:
if (monday.isAfter(end)) {
totalDates = List.of();
}
After that, you can get a sequence of Mondays with the convenient datesUntil method:
totalDates = monday.datesUntil(end, Period.ofWeeks(1)).collect(Collectors.toList());
Note that datesUntil does not include the end date. If you need the end date included, pass in end.plusDays(1).

You need to use getDayOfWeek(), here is the solution:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class AllMondays {
public static void main(String[] args) {
String s = "2020-07-20";
String e = "2020-09-20";
LocalDate start = LocalDate.parse(s);
LocalDate end = LocalDate.parse(e);
List<LocalDate> totalDates = new ArrayList<>();
LocalDate nextMonday = start;
int daysToAdvance = 1;
while (!nextMonday.isAfter(end)) {
if (nextMonday.getDayOfWeek() == DayOfWeek.MONDAY) {
daysToAdvance = 7;
totalDates.add(nextMonday);
}
nextMonday = nextMonday.plusDays(daysToAdvance);
}
System.out.println(totalDates);
}
}

You can use .getDayOfWeek() to get DayOfWeek and compare with DayOfWeek.MONDAY
while (!start.isAfter(end)) {
if(start.getDayOfWeek().equals(DayOfWeek.MONDAY)) {
totalDates.add(start);
}
start = start.plusDays(1);
}
And optimization is use start.plusWeeks(1) instead of start.plusDays(1) and you need to get the next monday before.
start = start.with(TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY));
while (!start.isAfter(end)) {
if(start.getDayOfWeek().equals(DayOfWeek.MONDAY)) {
totalDates.add(start);
}
start = start.plusWeeks(1);
}

Here "find_day" is the day you want to find in date range
SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault());
Date sub_start_date = format1.parse("01-06-2021");
Date enddate = format1.parse("30-06-2021");
Calendar min_date_c = Calendar.getInstance();
min_date_c.setTime(sub_start_date);
Calendar max_date_c = Calendar.getInstance();
max_date_c.setTime(enddate);
for (Calendar loopdate = min_date_c; min_date_c.before(max_date_c); min_date_c.add(Calendar.DATE, 1), loopdate = min_date_c) {
int dayOfWeek = loopdate.get(Calendar.DAY_OF_WEEK);
// if (dayOfWeek == Calendar.MONDAY || dayOfWeek == Calendar.SATURDAY) {
if (dayOfWeek == find_day) {
Calendar[] disabledDays = new Calendar[1];
disabledDays[0] = loopdate;
Date newdate = loopdate.getTime();
String strDate = format1.format(newdate);
Log.e("DATES>>> ", "" + strDate);
}
}

Related

How to print next day using java

i have a method which has to print the next seven days but instead of printing next seven days it prints last seven days,
could some one help me fixing this please
here is the method i use,
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class TestCalandar
{
public static void main(String[] args)
{
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE");
String date[] = null;
date = df.format(new Date()).split("/");
Calendar cal = Calendar.getInstance();
cal.set(Integer.parseInt(date[2]), Integer.parseInt(date[0]) - 1, Integer.parseInt(date[1]));
Map<String, String> currentWeekMap = new HashMap<String, String>();
for (int i = Calendar.SUNDAY; i <= Calendar.SATURDAY; i++)
{
cal.set(Calendar.DAY_OF_WEEK, i);
currentWeekMap.put(dayFormat.format(cal.getTime()), df.format(cal.getTime()));
}
System.out.println(currentWeekMap);
}
}
Use the new Java8 time API. This will accomplish what your code was trying to.
Map<String, String> currentWeekMap = new HashMap<>();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
LocalDate today = LocalDate.now();
for (int i=1; i<=7; i++) {
LocalDate newDay = today.plusDays(i);
String dayOfWeek = newDay.getDayOfWeek().toString();
String formattedDate = newDay.format(formatter);
currentWeekMap.put(dayOfWeek, formattedDate);
}
System.out.println(currentWeekMap);
I really short example
public class DateUtils {
private DateUtils() {}
public static Date addDays(Date baseDate, int daysToAdd) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(baseDate);
calendar.add(Calendar.DAY_OF_YEAR, daysToAdd);
return calendar.getTime();
}
}
Here's the solution which should output what you want :). Hope it helps!
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
class TestCalandar
{
public static void main(String[] args){
Calendar now = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
String[] days = new String[7];
int delta = now.get(Calendar.DAY_OF_WEEK)-6;
now.add(Calendar.DAY_OF_MONTH, delta );
for (int i = 0; i < 7; i++)
{
days[i] = format.format(now.getTime());
now.add(Calendar.DAY_OF_MONTH, 1);
}
for(int i = 0 ; i < days.length ; i++){
System.out.println(days[i]);
}
}
}
The method Calendar.set sets the specified field, in this case the DAY_OF_WEEK field, to the specified value. The effect on the other fields is dependent on other factors, more specifically, the effect of Calendar.set is to change the day of week and the adjustment will happen within the current WEEK_OF_YEAR. This behavior is dependent on the locale that the code is running in.
Instead you, need to add a day, so you could use the Calendar.add method.
cal.set(Calendar.DAY_OF_WEEK, i)
could change to:
cal.add(Calendar.DAY_OF_YEAR, 1);
which will add one day to the day for every iteration of the loop.
If the output is required to be printed in order, then printing on each iteration of the loop would be better than putting into the HashMap, as HashMaps are not ordered.
Also, you state that your requirement is to print the next 7 days, so the first day should be tomorrow, which would mean that you can remove the following line. When you call Calendar.getInstance(), the date is automatically set to the current time in the current time zone, so you just want to start adding to the calendar from right now, which means the first date will be tomorrow.
cal.set(Integer.parseInt(date[2]), Integer.parseInt(date[0]) - 1, Integer.parseInt(date[1]));
See here: http://www.tutorialspoint.com/java/util/calendar_add.htm for the first search on Calendar.add in google.
Here is the working one,
public static void main(String[] args) {
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE");
String date[] = null;
date = df.format(new Date()).split("/");
Calendar cal = Calendar.getInstance();
cal.set(Integer.parseInt(date[2]), Integer.parseInt(date[0]), Integer.parseInt(date[1]));
Map<String, String> currentWeekMap = new HashMap<String, String>();
for (int i = Calendar.SUNDAY; i <= Calendar.SATURDAY; i++) {
cal.add(Calendar.DATE, 1);
currentWeekMap.put(dayFormat.format(cal.getTime()), df.format(cal.getTime()));
}
System.out.println(currentWeekMap);
}

How can I create a calculation to get the age of a person from two dates?

I am trying to make a method that will calculate the age of a person. I want the calculation to be done under the second public static int getAge. If the person is born after the current date i want it to print out error -1.
How do I compare the two SimpleDate values dateBd and dateRef in order to get an int value for age?
public static SimpleDate today() {
Calendar todayCal = Calendar.getInstance();
SimpleDate todayDate = new SimpleDate();
todayDate.setDate(todayCal.get(Calendar.MONTH) + 1,
todayCal.get(Calendar.DATE),
todayCal.get(Calendar.YEAR));
return todayDate;
public static int getAge(SimpleDate dateBd) {
int age;
SimpleDate dateToday = today();
age = getAge(dateBd, dateToday);
return age;
public static int getAge(SimpleDate dateBd, SimpleDate dateRef) {
if(getAge(dateBd)>getAge(dateRef)){
system.out.println("error");
}
return -1;
What is SimpleDate ? Anyway here something to get you started
import java.util.GregorianCalendar;
import java.util.Calendar;
public class CalcAge {
public static void main(String [] args) {
// remember ... months are 0-based : jan=0 feb=1 ...
System.out.println
("1962-11-11 : " + age(1962,10,11));
System.out.println
("1999-12-03 : " + age(1999,11,3));
}
private static int age(int y, int m, int d) {
Calendar cal = new GregorianCalendar(y, m, d);
Calendar now = new GregorianCalendar();
int res = now.get(Calendar.YEAR) - cal.get(Calendar.YEAR);
if((cal.get(Calendar.MONTH) > now.get(Calendar.MONTH))
|| (cal.get(Calendar.MONTH) == now.get(Calendar.MONTH)
&& cal.get(Calendar.DAY_OF_MONTH) > now.get(Calendar.DAY_OF_MONTH)))
{
res--;
}
return res;
}
}
Don't ever try and use the millisecond difference between two times to calculate the differences, there are just to many idiosyncrasies with date/time calculations which can cause all sorts of erroneous errors.
Instead, save yourself (alot) of time and use a dedicated library
Java 8
LocalDate start = LocalDate.of(1972, Month.MARCH, 8);
LocalDate end = LocalDate.now();
long years = ChronoUnit.YEARS.between(start, end);
System.out.println(years);
Which outputs 43
JodaTime
DateTime startDate = new DateTime(1972, DateTimeConstants.MARCH, 8, 0, 0);
DateTime endDate = new DateTime();
Years y = Years.yearsBetween(startDate, endDate);
int years = y.getYears();
System.out.println(years );
Which outputs 43
You can even use a Period to gain more granuarlity...
Period period = new Period(startDate, endDate);
PeriodFormatter hms = new PeriodFormatterBuilder()
.printZeroAlways()
.appendYears()
.appendSeparator(" years, ")
.appendMonths()
.appendSeparator(" months, ")
.appendDays()
.appendLiteral(" days")
.toFormatter();
String result = hms.print(period);
System.out.println(result);
Which prints 43 years, 1 months, 5 days

get list of dates which occurs between two dates

I am trying to get dates, which occurs in every 5 days from start date to end date.
Eg.
if start date= 11/10/2014 i.e MM/DD/YYYY format
and end date =11/26/2014
then my **expected output** is =
[11/15/2014,11/20/2014,11/25/2014]
I tried below but very confuse where to run loop for getting exact ouput. Currently from below code i am only getting 1 date in list
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class TestDate {
// mm/dd/yyyy
public List getDates(Date fromDate,int frequency,Date endDate){
List list=new ArrayList<Date>();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Calendar c = Calendar.getInstance();
c.setTime(fromDate); // Now use today date.
c.add(Calendar.DATE, frequency); // Adding 5 days
String newDate = sdf.format(c.getTime());
String sEndDate=sdf.format(endDate);
if((newDate.compareTo(sEndDate) < 0) || (newDate.compareTo(sEndDate) == 0)){
list.add(newDate);
}
//Weekly=7,Bi-Weekly14,Monthly-30,Semi-Monthly-15
return list;
}
public static void main(String[] args) {
try {
TestDate obj=new TestDate();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date s = sdf.parse("11/10/2014");
Date e = sdf.parse("11/26/2014");
System.out.println(obj.getDates(s, 5, e));
}
catch(Exception e) {
System.err.println("--exp in main---"+e);
}
}
}
Correct answer is below *Thanks to Almas*
public List getDates(Date fromDate,int frequency,Date e){
List list=new ArrayList<Date>();
Calendar c = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c2.setTime(e); // Now use today date.
Date endDate=c2.getTime();
Date newDate=fromDate;
while(true){
c.add(Calendar.DATE, frequency);
newDate=c.getTime();
if(newDate.compareTo(endDate)<=0){
list.add(newDate);
}else{
break;
}
}
//Weekly=7,Bi-Weekly14,Monthly-30,Semi-Monthly-15
return list;
}
Why do you want date to be as string and compared lexicographically instead of comparing them as date?
String newDate = sdf.format(c.getTime());
String sEndDate=sdf.format(endDate);
This should be changed as
Date newDate = c.getTime();
Also you are using two if condition which you could do in one like below :
if (newDate.compareTo(endDate) <= 0) {
list.add(newDate);
}
as far as looping is concerned you should do it in your getDates method like below:
Date newDate;
while (true) {
c.add(Calendar.DATE, frequency); // Adding 5 days
newDate = c.getTime();
if (newDate.compareTo(endDate) <= 0) {
list.add(newDate);
} else {
break;
}
}
Make use of Apache commons DateUtils. This will make your code simple
Date tempDate = DateUtils.addDays(fromDate, frequency);
while (tempDate.before(endDate))
{
list.add(tempDate);
tempDate = DateUtils.addDays(tempDate, frequency);
}
return list;
try this one
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class NewClass1 {
// mm/dd/yyyy
public List getDates(Date fromDate, int frequency, Date endDate) {
List list = new ArrayList<Date>();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Calendar c = Calendar.getInstance();
c.setTime(fromDate); // Now use today date.
c.add(Calendar.DATE, frequency); // Adding 5 days
String newDate = sdf.format(c.getTime());
//System.out.println("date"+newDate);
String formDate = sdf.format(fromDate);
String sEndDate = sdf.format(endDate);
int x = 1;
while (((newDate.compareTo(sEndDate) > 0) || (newDate.compareTo(sEndDate) != 0)) && x < frequency) {
c.add(Calendar.DATE, frequency);
sEndDate = sdf.format(c.getTime());
x++;
System.out.println("date: " + sEndDate);
list.add(newDate);
}
//Weekly=7,Bi-Weekly14,Monthly-30,Semi-Monthly-15
return list;
}
public static void main(String[] args) {
try {
NewClass1 obj = new NewClass1();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date s = sdf.parse("11/10/2014");
Date e = sdf.parse("11/26/2014");
obj.getDates(s, 5, e);
} catch (Exception e) {
System.err.println("--exp in main---" + e);
}
}
}

How to get every day except weekend or Saturday or Sunday between two dates in java?

hi all how to generate dates if the start date and end date are provided in java?
like the following :
Ex : if the start date is 15-04-2012 and end date is 15-06-2012 having this i want dates to be like the following and the list should omit saturday and sunday
1.15-04-2012,
2.16-04-2012,
3.17-04-2012,
.
.
.
.
.
.
15-06-2012
I have done like the following but it will generate for one month if the date range is of same month.
`
public static ConcurrentHashMap<String, String> getWorkingDaysMap(int year, int month, int day){
int totalworkingdays=0,noofdays=0;
String nameofday = "";
ConcurrentHashMap<String,String> workingDaysMap = new ConcurrentHashMap<String,String>();
Map<String,String> holyDayMap = new LinkedHashMap<String,String>();
noofdays = findNoOfDays(year,month,day);
for (int i = 1; i <= noofdays; i++) {
Date date = (new GregorianCalendar(year,month - 1, i)).getTime(); // year,month,day
SimpleDateFormat f = new SimpleDateFormat("EEEE");
nameofday = f.format(date);
String daystr="";
String monthstr="";
if(i<10)daystr="0";
if(month<10)monthstr="0";
String formatedDate = daystr+i+"/"+monthstr+month+"/"+year;
if(!(nameofday.equals("Saturday") || nameofday.equals("Sunday"))){
workingDaysMap.put(formatedDate,formatedDate);
totalworkingdays++;
}
}
return workingDaysMap;
}
So please do advice me how to go about.
Regards
Tony
int noOfDaysBetween = 5;
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
for(int index = 0 ; index < noOfDaysBetween; index++){
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if( dayOfWeek!=Calendar.SUNDAY && dayOfWeek!=Calendar.SATURDAY) {
System.out.println(cal.getTime());
}
cal.add(Calendar.DATE, 1);
}
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
//15-04-2012
calendar.set(Calendar.DAY_OF_MONTH, 15);
calendar.set(Calendar.YEAR, 2012);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MONTH, 3);
Date start = calendar.getTime();
//15-06-2012
calendar.set(Calendar.MONTH, 5);
Date end = calendar.getTime();
calendar.setTime(start);
Date d = null;
while((d = calendar.getTime()).before(end) || d.equals(end)) {
int day = calendar.get(Calendar.DAY_OF_WEEK);
if (day != Calendar.SATURDAY && day != Calendar.SUNDAY) {
System.out.println(d);
}
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
}
I prefer usage of LocalDate.
import java.time.DayOfWeek;
import java.time.LocalDate;
public class Game {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2018, 6, 1);
LocalDate end = LocalDate.of(2018, 8, 1);
LocalDate d = start;
while(d.compareTo(end) <= 0) {
if (d.getDayOfWeek() != DayOfWeek.SATURDAY && d.getDayOfWeek() != DayOfWeek.SUNDAY) {
System.out.println(d);
}
d = d.plusDays(1);
}
}
}
use the following joda-time
import org.joda.time.DateTimeConstants;
import org.joda.time.LocalDate;
public class DatesexcludingWeekend {
public static void main(String[] args) {
final LocalDate start = new LocalDate(2012, 06, 15);
final LocalDate end = new LocalDate(2012, 07, 14);
LocalDate weekday = start;
if (start.getDayOfWeek() == DateTimeConstants.SATURDAY|| start.getDayOfWeek() == DateTimeConstants.SUNDAY) {
weekday = weekday.plusWeeks(1).withDayOfWeek(DateTimeConstants.MONDAY);
}
while (weekday.isBefore(end)) {
System.out.println(weekday);
if (weekday.getDayOfWeek() == DateTimeConstants.FRIDAY)
weekday = weekday.plusDays(3);
else
weekday = weekday.plusDays(1);
}
}

Java calendar getting weekdays not working

I am trying to get this to output all the weekdays (MON-FRI) between 5/16/2010 (a sunday) and 5/25/2010 (a tuesday). The correct output should be 17,18,19,20,21,24,25. However, the result im getting is 17,18,19,20,21,17,18,19. The other methods just split up the string the date is in
import java.util.*;
public class test
{
public static void main(String[] args) {
String startTime = "5/16/2010 11:44 AM";
String endTime = "5/25/2010 12:00 PM";
GregorianCalendar startCal = new GregorianCalendar();
startCal.setLenient(true);
String[] start = splitString(startTime);
//this sets year, month day
startCal.set(Integer.parseInt(start[2]),Integer.parseInt(start[0])-1,Integer.parseInt(start[1]));
startCal.set(GregorianCalendar.HOUR, Integer.parseInt(start[3]));
startCal.set(GregorianCalendar.MINUTE, Integer.parseInt(start[4]));
if (start[5].equalsIgnoreCase("AM")) { startCal.set(GregorianCalendar.AM_PM, 0); }
else { startCal.set(GregorianCalendar.AM_PM, 1); }
GregorianCalendar endCal = new GregorianCalendar();
endCal.setLenient(true);
String[] end = splitString(endTime);
endCal.set(Integer.parseInt(end[2]),Integer.parseInt(end[0])-1,Integer.parseInt(end[1]));
endCal.set(GregorianCalendar.HOUR, Integer.parseInt(end[3]));
endCal.set(GregorianCalendar.MINUTE, Integer.parseInt(end[4]));
if (end[5].equalsIgnoreCase("AM")) { endCal.set(GregorianCalendar.AM_PM, 0); }
else { endCal.set(GregorianCalendar.AM_PM, 1); }
for (int i = startCal.get(Calendar.DATE); i < endCal.get(Calendar.DATE); i++)
{
startCal.set(Calendar.DATE, i);
startCal.set(Calendar.DAY_OF_WEEK, i);
if (startCal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY)
{
System.out.println("\t" + startCal.get(Calendar.DATE));
}
}
}
private static String[] splitDate(String date)
{
String[] temp1 = date.split(" "); // split by space
String[] temp2 = temp1[0].split("/"); // split by /
//5/21/2010 10:00 AM
return temp2; // return 5 21 2010 in one array
}
private static String[] splitTime(String date)
{
String[] temp1 = date.split(" "); // split by space
String[] temp2 = temp1[1].split(":"); // split by :
//5/21/2010 10:00 AM
String[] temp3 = {temp2[0], temp2[1], temp1[2]};
return temp3; // return 10 00 AM in one array
}
private static String[] splitString(String date)
{
String[] temp1 = splitDate(date);
String[] temp2 = splitTime(date);
String[] temp3 = new String[6];
return dateFill(temp3, temp2[0], temp2[1], temp2[2], temp1[0], temp1[1], temp1[2]);
}
private static String[] dateFill(String[] date, String hours, String minutes, String ampm, String month, String day, String year) {
date[0] = month;
date[1] = day;
date[2] = year;
date[3] = hours;
date[4] = minutes;
date[5] = ampm;
return date;
}
private String dateString(String[] date) {
//return month+" "+day+", "+year+" "+hours+":"+minutes+" "+ampm
//5/21/2010 10:00 AM
return date[3]+"/"+date[4]+"/ "+date[5]+" "+date[0]+":"+date[1]+" "+date[2];
}
}
startCal.set(Calendar.DAY_OF_WEEK, i); Will flip flip your date back every 7 loops.
This code isn't good.
I don't understand why you're doing all this parsing of Strings to get to Date and visa versa when you have java.text.DateFormat and java.text.SimpleDateFormat to do it easily for you.
I think this is better. See if you agree:
package com.contacts.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class DateUtils
{
private static final DateFormat DEFAULT_FORMAT = new SimpleDateFormat("dd-MMM-yyyy");
public static void main(String[] args)
{
try
{
Date startDate = ((args.length > 0) ? DEFAULT_FORMAT.parse(args[0]) : new Date());
Date endDate = ((args.length > 1) ? DEFAULT_FORMAT.parse(args[1]) : new Date());
List<Date> weekdays = DateUtils.getWeekdays(startDate, endDate);
Calendar calendar = Calendar.getInstance();
for (Date d : weekdays)
{
calendar.setTime(d);
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);
// System.out.println(DEFAULT_FORMAT.format(d));
System.out.println("day: " + dayOfMonth + " month: " + (month+1) + " year: " + year);
}
}
catch (ParseException e)
{
e.printStackTrace();
}
}
public static List<Date> getWeekdays(Date startDate, Date endDate)
{
List<Date> weekdays = new ArrayList<Date>();
if ((startDate == null) || (endDate == null))
return weekdays;
if (startDate.equals(endDate))
{
if (isWeekday(startDate))
{
weekdays.add(startDate);
}
}
else if (startDate.after(endDate))
{
weekdays = getWeekdays(endDate, startDate);
}
else
{
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
Date d = startDate;
while (endDate.equals(d) || endDate.after(d))
{
if (isWeekday(d))
{
weekdays.add(d);
}
calendar.add(Calendar.DATE, 1);
d = calendar.getTime();
}
}
return weekdays;
}
public static boolean isWeekday(Date d)
{
if (d == null)
return false;
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
return ((dayOfWeek >= Calendar.MONDAY) && (dayOfWeek <= Calendar.FRIDAY));
}
}
I don't know if this is an issue with your code, but JDK uses some unexpected values for Calendar constants. For example, months star with zero. In other words, Calendar.JANUARY is 0. On the other hand, weekdays are 1 to 7, starting with Sunday as 1. etc.
I luckily don't know much about Date in Java, but I know it's basically a difficult and bad API. Go for JodaTime until the new JSR-310 is done.

Categories