Need assistance with attributes in Java - java

What I'm trying to do is access an object, in this case date1 which has 3 attributes day, month and year. I'm attempting to make a method called showTomorrow() which will display the objects information 1 day infront in String format. This means I cannot alter the attributes of the original object.
I've written the Data.java program and it's shown below, if someone could point me in the right direction or show me what it would be really helpfull.
This is what I'd essentially be running on my main method I believe.
**Date date1 = new Date(30, 12, 2013)** // instantiate a new object with those paramaters
**date1.showDate();** // display the original date
**date1.tomorrow();** // shows what that date would be 1 day infront
The problem is right now it's not displaying anything. I thought that by saying dayTomorrow = this.day++; I was adding it's default value + 1 day to the variable dayTomorrow.
public class Date
{
private int day;
private int month;
private int year;
private int dayTomorrow;
private int monthTomorrow;
private int yearTomorrow;
public Date()
{
day = 1;
month = 1;
year = 1970;
}
public Date(int inDay, int inMonth, int inYear)
{
day = inDay;
month = inMonth;
year = inYear;
}
public void setDate(int inDay, int inMonth, int inYear)
{
day = inDay;
month = inMonth;
year = inYear;
}
public String getDate()
{
String strDate;
strDate = day + "/" + month + "/" + year;
return strDate;
}
public String getTomorrow()
{
String strTomorrow;
strTomorrow = dayTomorrow + "/" + monthTomorrow + "/" + yearTomorrow;
return strTomorrow;
}
public String tomorrow()
{
dayTomorrow = this.day++;
monthTomorrow = this.month;
yearTomorrow = this.year;
if(dayTomorrow > 30)
{
dayTomorrow = 1;
monthTomorrow = this.month++;
}
if(monthTomorrow > 12)
{
monthTomorrow = 1;
yearTomorrow = this.year++;
}
return getTomorrow();
}
public void showDate()
{
System.out.print("\n\n THIS OBJECT IS STORING ");
System.out.print(getDate());
System.out.print("\n\n");
}
public void showTomorrow()
{
System.out.print("\n\n THE DATE TOMORROW IS ");
System.out.print(getTomorrow());
System.out.print("\n\n");
}
public boolean equals(Date inDate)
{
if(this.day == inDate.day && this.month == inDate.month && this.year == inDate.year)
{
return true;
}
else
{
return false;
}
}
}

You just need to use ++this.day, ++this.month and ++this.year. When you use this.day++ it returns the previous date value, not the new. Putting the ++ in the front solves the problem. Also, it changes the day value... you might want to change that to this.day + 1.

Are You calling showDate() after date1.tomorrow() to show your output?
or instead of date1.tomorrow(); call date1.showTomorrow();

Have a look at this : http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html
post incremention ...

You could use the native date support in java but I figured you are just practicing right?
This should do the trick:
public class Date {
private int day = 1;
private int month = 1;
private int year = 1970;
private int dayTomorrow = day+1;
private int monthTomorrow;
private int yearTomorrow;
public Date()
{
tomorrow();
}
public Date(int inDay, int inMonth, int inYear)
{
day = inDay;
month = inMonth;
year = inYear;
tomorrow();
}
public void setDate(int inDay, int inMonth, int inYear)
{
day = inDay;
month = inMonth;
year = inYear;
}
public String getDate()
{
String strDate;
strDate = day + "/" + month + "/" + year;
return strDate;
}
public String getTomorrow()
{
String strTomorrow;
strTomorrow = dayTomorrow + "/" + monthTomorrow + "/" + yearTomorrow;
return strTomorrow;
}
public void tomorrow()
{
monthTomorrow = this.month;
yearTomorrow = this.year;
if(dayTomorrow > 30)
{
dayTomorrow = 1;
monthTomorrow = this.month++;
}
if(monthTomorrow > 12)
{
monthTomorrow = 1;
yearTomorrow = this.year++;
}
}
public void showDate()
{
System.out.print("\n\n THIS OBJECT IS STORING ");
System.out.print(getDate());
System.out.print("\n\n");
}
public void showTomorrow()
{
System.out.print("\n\n THE DATE TOMORROW IS ");
System.out.print(getTomorrow());
System.out.print("\n\n");
}
public boolean equals(Date inDate)
{
if(this.day == inDate.day && this.month == inDate.month && this.year == inDate.year)
{
return true;
}
else
{
return false;
}
}
}
Look carefully for any changes i've made ;)
Here's the main:
public static void main(String[] args) {
Date d = new Date();
d.showDate();
d.showTomorrow();
}

Related

Filtering the result based on max date using Hazelcast jet

How to filter the BatchStage result based on max date.
Here is my code..
BatchStage<TestModel> testModel = value.map(model -> JsonUtil.mapFrom(model.getObject_value()))
.map(json -> new TestModel(json.get("id"), json.get("json_obs")));
Here is the model class
public class TestModel implements Serializable {
private Object key;
private Object value;
//getters and setter
// HashCode and equals method
}
In the console I'm currently getting this output
TestModel [key=0001, value=[{date=09/03/2021}, {date=10/03/2021}]]
TestModel[key=0002, value=[{date=09/03/2021}, {date=11/03/2021}]]
Now I wants to keep only the max date map in the value object
example:-
TestModel [key=0001, value=[{date=10/03/2021}]]
TestModel[key=0002, value=[{date=11/03/2021}]]
Any suggestions would be helpful.
All you need to do is to write a function, which need to get the max date in a list of date.
And I think i need to know the type of "date"...
if it is the type of "java.util.Date", the function can be like this:
public static Date getMaxDate(List<Date> dates) {
if (dates.size() == 0) {
throw new RuntimeException("No date value in list...");
}
Date max = dates.get(0);
for (Date date : dates) {
//use the implemented compareTo() function
if (max.compareTo(date) < 0) {
max = date;
}
}
return max;
}
if it is a type of "java.time.LocalDate" the function can be like this:
public static LocalDate getMaxLocalDate(List<LocalDate> dates) {
if (dates.size() == 0) {
throw new RuntimeException("No date value in list...");
}
LocalDate max = dates.get(0);
for (LocalDate date : dates) {
//use isBefore function
if (max.isBefore(date)) {
max = date;
}
}
return max;
}
and if it is your own type, defined like:
public class MyDate {
public int year;
public int month;
public int day;
public MyDate() {
}
public MyDate(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
#Override
public String toString() {
return "MyDate{" +
"year=" + year +
", month=" + month +
", day=" + day +
'}';
}
}
then the function can be like this:
public static MyDate getMaxMyDate(List<MyDate> dates) {
if (dates.size() == 0) {
throw new RuntimeException("No date value in list...");
}
MyDate max = dates.get(0);
LocalDate maxLocalDate = LocalDate.of(max.year, max.month, max.day);
for (MyDate date : dates) {
//convert to LocalDate to compare
LocalDate currentLocalDate = LocalDate.of(date.year, date.month, date.day);
if (maxLocalDate.isBefore(currentLocalDate)) {
max = date;
maxLocalDate = LocalDate.of(max.year, max.month, max.day);
}
}
return max;
}
and it seems that you need to get a result as list, you can use List.of(max) to get a list result.

Need time difference with string like "A Min ago" or "An Hour Ago" [duplicate]

This question already has answers here:
How to calculate "time ago" in Java?
(33 answers)
Closed 8 years ago.
I am new in Android Development.
I need one help to convert my current time with one static time.
Your help be appreciated.
I have one string like this
String created_at = "Wed Mar 03 19:37:35 +0000 2010";
I want to convert it like , which means difference between my current time and created_at string.
23 mins ago // Example
Thanks,
Dharmik
Just use the following utility class I've created and pass the two date objects in its constructor .Subsequently use the getDifferenceString() method to obtain the same.
public class TimeDifference {
int years;
int months;
int days;
int hours;
int minutes;
int seconds;
String differenceString;
public TimeDifference(Date curdate, Date olddate) {
float diff=curdate.getTime() - olddate.getTime();
if (diff >= 0) {
int yearDiff = Math.round( ( diff/ (365l*2592000000f))>=1?( diff/ (365l*2592000000f)):0);
if (yearDiff > 0) {
years = yearDiff;
setDifferenceString(years + (years == 1 ? " year" : " years") + " ago");
} else {
int monthDiff = Math.round((diff / 2592000000f)>=1?(diff / 2592000000f):0);
if (monthDiff > 0) {
if (monthDiff > 11)
monthDiff = 11;
months = monthDiff;
setDifferenceString(months + (months == 1 ? " month" : " months") + " ago");
} else {
int dayDiff = Math.round((diff / (86400000f))>=1?(diff / (86400000f)):0);
if (dayDiff > 0) {
days = dayDiff;
if(days==30)
days=29;
setDifferenceString(days + (days == 1 ? " day" : " days") + " ago");
} else {
int hourDiff = Math.round((diff / (3600000f))>=1?(diff / (3600000f)):0);
if (hourDiff > 0) {
hours = hourDiff;
setDifferenceString( hours + (hours == 1 ? " hour" : " hours") + " ago");
} else {
int minuteDiff = Math.round((diff / (60000f))>=1?(diff / (60000f)):0);
if (minuteDiff > 0) {
minutes = minuteDiff;
setDifferenceString(minutes + (minutes == 1 ? " minute" : " minutes") + " ago");
} else {
int secondDiff =Math.round((diff / (1000f))>=1?(diff / (1000f)):0);
if (secondDiff > 0)
seconds = secondDiff;
else
seconds = 1;
setDifferenceString(seconds + (seconds == 1 ? " second" : " seconds") + " ago");
}
}
}
}
}
}
}
public String getDifferenceString() {
return differenceString;
}
public void setDifferenceString(String differenceString) {
this.differenceString = differenceString;
}
public int getYears() {
return years;
}
public void setYears(int years) {
this.years = years;
}
public int getMonths() {
return months;
}
public void setMonths(int months) {
this.months = months;
}
public int getDays() {
return days;
}
public void setDays(int days) {
this.days = days;
}
public int getHours() {
return hours;
}
public void setHours(int hours) {
this.hours = hours;
}
public int getMinutes() {
return minutes;
}
public void setMinutes(int minutes) {
this.minutes = minutes;
}
public int getSeconds() {
return seconds;
}
public void setSeconds(int seconds) {
this.seconds = seconds;
}
}
its is simple do something like this ( Note I don't have java etc installed I have just typed it in Note on my ipad, so I am not sure if it works but it should be something like this) :
String dateString = "Wed Mar 03 19:37:35 2010";
SimpleDateFormat dateFormat = new SimpleDateFormat("E M d hh:mm:ss y");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(dateString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// convert date to calnedar
Calendar previouseCal = Calendar.getInstance();
previouseCal.setTime(convertedDate );
// then get the current time
Calendar currentCal = Calendar.getInstance();
// then get the diffrence
long difference = currentCal.getTimeInMillis() - previouseCal.getTimeInMillis();
// if you need it in second then
int second = TimeUnit.MILLISECONDS.toSeconds(difference)
I hope that helps :)

I want to edit the fourth variable of my class, but I seem to edit them all

What my program does now:
I create a person object with the following information: firstname, lastname, birthdate (the data is different class).
The date class, has four variables: day, month, year and 18+ (yes or no).
What does work: I can create a person object with a firstname, lastname and birthdate succesfully.
My person class (what looks like it works).
public class Person {
public String firstName;
public String lastName;
public Date date;
public String toString() {
return (firstName + " " + lastName + " (" + date);
}
public Person(String firstName, String lastName, Date date) {
this.firstName = firstName;
this.lastName = lastName;
this.date = date;
}
}
MY class including my main, where I also have a method where I create my person(s).
public static Person setName() {
String name;
String lastName
String inputBirthdate;
Date niceDate
Date newDate;
System.out.println("Firstname:");
firstName = userInput();
System.out.println("Lastname:");
lastName = userInput();
System.out.println("Birthday:");
inputBirthdate = userInput();
niceDate = new Date(inputBirthdate);
newDate = new Date(niceDate);
return new Gast(firstName, lastName, newDate);
}
And then I have my Date class, where I check if the input of the date is correct. Please not that I can get my Date class to work correctly WITHOUT the 4th variable.
public class Date {
public String day;
public String month;
public String year;
public boolean child;
public String toString() {
return (day + "." + month + "." + year + "." + child);
}
/*Date(String day, String month, String year, boolean child) {
this.day = dag;
this.month = month;
this.year = year;
this.child = child;
}*/ //don't need this one, output is the same
public Date(Datum niceDate) {
int bYear = Integer.parseInt(niceDate.year;
int bMonth = Integer.parseInt(niceDate.day);
int bDay = Integer.parseInt(niceDate.day);
boolean child = false;
if (bYear > 1995) {
this.child= true;
} else if (bYear == 1995 && bMonth > 10) {
this.child = true;
} else if (bYear == 1995 && bMonth == 10 && bDay > 1) {
this.child = true;
} else {
this.child = false;
}
}
public Date(String birthdate) {
String patroon = "\\d{2}-\\d{2}-\\d{4}";
boolean b = birthdate.matches(patroon);
if (b) {
String[] str = birthdate.split("-");
for (String s: str)
this.day = str[0];
this.month = str[1];
this.year = str[2];
}
else {
System.out.println("Birthday is formatted wrong");
}
}
}
If I run this (witch the check of adult or not (the check looks like it work!), However, my input of the birthdate returns null:
Room 1: Name name (null.null.null)false //boolean works, date not
Room 2: available
I think the problem is that in my second method in my Date class, the public Date(Date Nicedate) deletes my date after parsing it to an int.
So basically I only want to return the Boolean and keep my Strings exactly the same, and only editing them for using them as an Int for the calculations.
Can someone point me in the right direction? Probably it's a very simple solution, but I've been working on it all day and don't see the solution.
EDIT AS REQUESTED: (I've the this statements in the public Date(datum niceDate) but the date still won't show. Hmmmmm:
public Date(Datum niceDate) {
this.year = year;
this.day = day;
this.month = month;
int bYear = Integer.parseInt(niceDate.year;
int bMonth = Integer.parseInt(niceDate.day);
int bDay = Integer.parseInt(niceDate.day);
boolean child = false;
if (bYear > 1995) {
this.child= true;
} else if (bYear == 1995 && bMonth > 10) {
this.child = true;
} else if (bYear == 1995 && bMonth == 10 && bDay > 1) {
this.child = true;
} else {
this.child = false;
}
}
public Date(String birthdate) {
String patroon = "\\d{2}-\\d{2}-\\d{4}";
boolean b = birthdate.matches(patroon);
if (b) {
String[] str = birthdate.split("-");
for (String s: str)
this.day = str[0];
this.month = str[1];
this.year = str[2];
}
else {
System.out.println("Birthday is formatted wrong");
}
}
}
The problem is that when you create newDate from niceDate, you are not copying the day/month/year.
If you look in your public Date(Datum niceDate) constructor, the only instance variable that you set is this.child, but you also need to set this.day, this.month, and this.year.
Also, I recommend you instead create a function for the date calculation called isAdult as a method of your Date class, and just call niceDate.isAdult() if you need to show whether the date is 18+ years ago. Otherwise, it's easy to make a mistake and have this.child be incorrect.
public Date(Datum niceDate) {
this.year = year;
In this constructor, this.year and year refer to the same member variable. So you are assigning the value of that variable to itself.
Then later you do
int bYear = Integer.parseInt(niceDate.year);
which parses the value from niceDate and assigns its value to a local variable named bYear. Instead, you need to assign the result of parseInt to this.year:
this.year = Integer.parseInt(niceDate.year);
You can make similar changes to all of the other variables.

Java, Creating a calendar

In my Java class, I have to build a calendar application. I've got it mostly completed, however I need help with a couple of methods. I have commented the parts that I need help with. The code includes three classes and a main called TestCalendar. The functions I need help with are located in the Calendar class, named removeEvent(two of them, taking two different arguments), printEvents, and findEvents. Thanks in advance!
Here is the Date class.
public class Date {
int year, month, day;
//constructor
public Date(int yr, int mth, int dy){
year = yr;
if (yr < 2000 || yr > 2100)
{
System.out.println("Wrong Calander Year");
System.exit(1);
}
month = mth;
if (mth < 1 || mth > 12)
{
System.out.println("Wrong Month");
System.exit(1);
}
day = dy;
if (dy < 1 || dy > 31)
{
System.out.println("Wrong Day");
System.exit(1);
}
}
//accessor methods
public int getYear()
{
return year;
}
public int getMonth()
{
return month;
}
public int getDay()
{
return day;
}
//returns date in correct format
public String toString()
{
return "" + month + "/" + day + "/" + year;
}
}
Here is the Event class
public class Event {
Date date;
int hour;
String activity;
Event(int year, int month, int day, int hour, String activity)
{
if (year < 2000 || year > 2100)
{
System.out.println("Wrong Calander Year");
System.exit(1);
}
if (month < 1 || month > 12)
{
System.out.println("Wrong Month");
System.exit(1);
}
if (day < 1 || day > 31)
{
System.out.println("Wrong Day");
System.exit(1);
}
this.date = new Date(year, month, day);
this.hour = hour;
this.activity = activity;
}
public Date getDate()
{
return date;
}
public int getHour()
{
return hour;
}
public String getActivity()
{
return activity;
}
void setActivity(String newActivity)
{
this.activity = newActivity;
}
public String toString()
{
return "" + date +" " + "#" + hour +":" + " " + activity;
}
public boolean equals(Object obj)
{
if (obj instanceof Event)
{
return true;
}
else return false;
}
}
The Calendar class
public class Calander {
static final int MAXEVENTS = 10;
Event[] events;
int numEvents;
// constructor
public Calander() {
numEvents = 0;
events = new Event[MAXEVENTS];
}
void addEvent(int year, int month, int day, int hour, String activity) {
Event newEvent = new Event(year, month, day, hour, activity);
events[numEvents] = newEvent;
numEvents++;
}
void removeEvent(int year, int month, int day, int hour, String activity) {
{
if (events[numEvents] == null);
numEvents--;
}
}
// instructions say to remove (all) Event objects in the Calendar that are equals to the event argument. Use the equals method from the event class
void removeEvent(Event event) {
//what to put here?
}
// this method needs to print every Event in the associated Calendar that matches the date arguments. Print each on a separate line, using the toString method from the Event class.
void printEvents(int year, int month, int day) { // how to set equality
if (this.events[numEvents] == )
{
// what to put here?
}
}
// same as above but matches the (Date date) arguments
void printEvents(Date date) {
toString();
}
// Return the first Event in the Calendar that has a matching (equals) activity field. If no match is found, you must return a reference type, so return null.
Event findEvent(String activity) {
//what to put here?
return null;
}
void dump() {
for (int i = 0; i < MAXEVENTS; i++)
{
if (events[i] != null)
System.out.println(events[i]);
}
}
}
well, your event class has a method:
public boolean equals(Object obj)
Which, presumably, should return whether or not the passed event is equal to the instance.
So your void removeEvent(Event event) method should look similar to the following:
take note that this is psudo-code and not valid java. you're going to have to flesh out the details on your own.
void removeEvent(Event event)
{
foreach(event e in this.events)
{
if(event.equals(e))
{
// remove e from the events array
}
}
}
The rest of the methods are going to more or less be similar in concept to the first one with 2 varying factorrs:
how you identify a match
what you do with the match
Since this is homework, I don't actually want to do your homework. So as a hint, you want to use (your event).equals(comparing to other event), not "==".

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