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);
}
}
}
Related
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);
}
}
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);
}
I am getting actual date using this:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
Calendar cal = Calendar.getInstance();
String today = dateFormat.format(cal.getTime());
System.out.println(today);
It prints today`s date: 21.04.2014
Then, I want to compare this date whether it is between two dates:
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
Date actualdate = sdf.parse(today);
Date date1 = sdf.parse("20.04.2014");
Date date2 = sdf.parse("23.04.2014");
Calendar actual = Calendar.getInstance();
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
actual.setTime(actualdate);
cal1.setTime(date1);
cal2.setTime(date2);
if(actual.after(date1) && actual.before(date2)) System.out.println("Yes");
else System.out.println("No");
It always prints No. What is the problem ? When I set date1 to 21.04.2014 and use actual.equals(date1) it works. But when I am using before or after it doesnt. Thanks
change it to actual.after(cal1) && actual.before(cal2)
you are comparing a calendar with dates
you must compare calendars with calendars or dates with dates
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Cal {
public static void main(String[] args) throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMyyyy");
Calendar cal = Calendar.getInstance();
String today = dateFormat.format(cal.getTime());
System.out.println(today);
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
Date actualdate = sdf.parse(today);
Date date1 = sdf.parse("20042014");
Date date2 = sdf.parse("23042014");
Calendar actual = Calendar.getInstance();
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
actual.setTime(actualdate);
cal1.setTime(date1);
cal2.setTime(date2);
System.out.println(actual);
System.out.println(cal1);
System.out.println(cal2);
if(actualdate.after(date1) && actualdate.before(date2)){
System.out.println("Yes");
}
else {
System.out.println("No");
}
if(actual.after(cal1) && actual.before(cal2)){
System.out.println("Yes");
}
else {
System.out.println("No");
}
}
}
I am sorry to tell you that the function that compares between two dates is useless and not working.
If you would like to have a go this is the function i tested
private static boolean validateEndDate(String startDate, String endDate)
{
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
Date date1 = dateFormat.parse(startDate);
Date date2 = dateFormat.parse(endDate);
if(date1.before(date2))
{
return true;
}
}catch(Exception e)
{
System.out.println(e.getMessage());
}
return false;
}
Now to see what i am talking about give it these two dates:
System.out.println(validateEndDate("31/07/2016","1/08/2016"));
Now to fix this problem i had to implement my own function:
private boolean compareDates(String startDate,String endDate)
{
int day=Integer.parseInt(startDate.split("/")[0]);
int month=Integer.parseInt(startDate.split("/")[1]);
int year=Integer.parseInt(startDate.split("/")[2]);
int day2=Integer.parseInt(endDate.split("/")[0]);
int month2=Integer.parseInt(endDate.split("/")[1]);
int year2=Integer.parseInt(endDate.split("/")[2]);
if(year<year2 || year==year2)
{
if(year<year2)
{
return true;
}
//Check the month
if(month<month2 || month==month2)
{
if(month<month2)
{
return true;
}
//Check the day
if(day<day2)
{
return true;
}
}
}
return false;
}
You are comparing Calender value with Date. Just use Date values. or just use Calender values. Don't mix them both.
actual.after(cal1) && actual.before(cal2)
or
actualdate.after(date1) && actualdate.before(date2)
see the working one:
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
Date actual = sdf.parse("21.04.2014");
Date date1 = sdf.parse("20.04.2014");
Date date2 = sdf.parse("23.04.2014");
if(actual.after(date1) && actual.before(date2)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
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);
}
}
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.