Leapday offset - cleaner solution anyone? - java

I needed to define start/end dates for a person's given age. This seemed simple:
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(dateOfBirth);
cal.add(Calendar.YEAR, years);
Date start = cal.getTime();
cal.add(Calendar.YEAR, 1);
cal.add(Calendar.DAY_OF_MONTH, -1);
Date end = cal.getTime();
Ah, but then there are those born on Leap Day Feb 29th. If the age is not a multiple of 4 then Calendar will round down to the 28th. In this case, my code above will give a date range ending on Feb 27th, and there'll be a gap.
So, I can easily solve this by checking for this condition, and I can wrap the fix up in some method to avoid duplicating it everywhere. But I'm wondering, is there a better solution I'm not aware of? Something that automatically accounts for this special case for a "day before/after" problem?
Here's my solution:
public static Date getAgeStartEnd(Date d, int age, boolean end) {
if (d == null) return null;
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(d);
int baseDay = cal.get(Calendar.DAY_OF_MONTH);
cal.add(Calendar.YEAR, age + (end ? 1 : 0));
int newDay = cal.get(Calendar.DAY_OF_MONTH);
boolean roundedDown = baseDay != newDay;
if (end && !roundedDown)
cal.add(Calendar.DAY_OF_MONTH, -1);
else if (!end && roundedDown)
cal.add(Calendar.DAY_OF_MONTH, 1);
d = cal.getTime();
return d;
}
Date start = getAgeStartEnd(dateOfBirth, years, false);
Date end = getAgeStartEnd(dateOfBirth, years, true);

Related

How can I increment the day with skipping weekends [duplicate]

This question already has answers here:
How can I add business days to the current date in Java?
(14 answers)
Closed 6 years ago.
How can I increment the day with skipping weekends. I mean if day=Friday then day+1=Monday. Please take a look at my increment method which I increment a calendar day and not a Business day
public Date incDay( Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, 1);
return cal.getTime();
}
I need to modify this method for resolve this issue.
Update:
I update my method like this
public Date incDay(Date date){
final Calendar cal = Calendar.getInstance();
cal.setTime(date);
// public final static int FRIDAY = 6;
final int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.FRIDAY) {
cal.add(Calendar.DATE, 3);
}else{
cal.add(Calendar.DATE, 1);
}
System.out.println(cal.getTime());
return cal.getTime();
}
Main():
public static void main(String[] args) throws ParseException {
Date d=incBusiness(new Date(2017, 02, 17));//2017/02/18
}
I got 2017/02/18 instead of 2017/02/20
Calendar class has constants to check the day of the week:
FRIDAY is the 6th day of the week, doing an if-else can resolve the issue...
public static void foo() throws ParseException {
String dateString = "2017/02/17";
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");// "2017/02/17";
Date date = df.parse(dateString);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
cal.add(Calendar.DATE, 3);
} else {
cal.add(Calendar.DATE, 1);
}
System.out.println(cal.getTime());
}
Gets date instance and add no. of days excluding weekends. Set date to next monday if provided date is weekend.
public Date addDays(Date date, int days){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
//set date to next monday if provided date day is weekend
//use this section according to your need.
if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY){
cal.add(Calendar.DATE,2);
//days-= 2;
}else if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY){
cal.add(Calendar.DATE,1);
//days--;
}
//add days one by one
while(days > 0){
//if current day is friday add 3 days to skip saturday and sunday
if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY){
cal.add(Calendar.DATE,3);
//else add one day
}else{
cal.add(Calendar.DATE,1);
}
//decrements day counter
days--;
}
return cal.getTime();
}

Get all dates in calendar in current month

How to get all dates in the calendar in current/some month?
for example for this month, like the picture
So the result is ["07-31-2016", "08-01-2016", "08-02-2016" ... "08-31-2016", "09-01-2016", "09-02-2016", "09-03-2016"]
Any ideas?, thanks in advance.
Well, with Calendar and its constants you can achieve this quite easy:
Given month and year get first day of the month and place calendar on monday:
Calendar start = Calendar.getInstance();
start.set(MONTH, month - 1); // month is 0 based on calendar
start.set(YEAR, year);
start.set(DAY_OF_MONTH, 1);
start.getTime(); // to avoid problems getTime make set changes apply
start.set(DAY_OF_WEEK, SUNDAY);
if (start.get(MONTH) <= (month - 1)) // check if sunday is in same month!
start.add(DATE, -7);
Given month and year get last day of month and move calendar to sunday
Calendar end = Calendar.getInstance();
end.set(MONTH, month); // next month
end.set(YEAR, year);
end.set(DAY_OF_MONTH, 1);
end.getTime(); // to avoid problems getTime make set changes apply
end.set(DATE, -1);
end.set(DAY_OF_WEEK, SATURDAY);
if (end.get(MONTH) != month)
end.add(DATE, + 7);
Test it:
public static void main(String[] args) {
int month = 8, year = 2016;
Calendar start = Calendar.getInstance();
start.set(MONTH, month - 1); // month is 0 based on calendar
start.set(YEAR, year);
start.set(DAY_OF_MONTH, 1);
start.getTime();
start.set(DAY_OF_WEEK, SUNDAY);
if (start.get(MONTH) <= (month - 1))
start.add(DATE, -7);
System.out.println(printCalendar(start));
Calendar end = Calendar.getInstance();
end.set(MONTH, month); // next month
end.set(YEAR, year);
end.set(DAY_OF_MONTH, 1);
end.getTime();
end.set(DATE, -1);
end.set(DAY_OF_WEEK, SATURDAY);
start.getTime();
if (end.get(MONTH) != month)
end.add(DATE, + 7);
System.out.println(printCalendar(end));
}
Combined with:
import static java.util.Calendar.*;
and
private final static SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
private static String printCalendar(Calendar c) {
return df.format(c.getTime());
}
OUTPUT:
2016/07/31
2016/09/03
WITH
int month = 5, year = 2015;
OUTPUT:
2015/04/26
2015/06/06
Now, just iterate over starting Calendar adding +1 to Calendar.DATE in a while loop (in the example I split by weeks to be more clear):
int i = 1;
while (start.before(end)) {
System.out.print(printCalendar(start));
if (i % 7 == 0) { // last day of the week
System.out.println();
i = 1;
} else {
System.out.print(" - ");
i++;
}
start.add(DATE, 1);
}
OUTPUT:
2015/04/26 - 2015/04/27 - 2015/04/28 - 2015/04/29 - 2015/04/30 - 2015/05/01 - 2015/05/02
2015/05/03 - 2015/05/04 - 2015/05/05 - 2015/05/06 - 2015/05/07 - 2015/05/08 - 2015/05/09
2015/05/10 - 2015/05/11 - 2015/05/12 - 2015/05/13 - 2015/05/14 - 2015/05/15 - 2015/05/16
2015/05/17 - 2015/05/18 - 2015/05/19 - 2015/05/20 - 2015/05/21 - 2015/05/22 - 2015/05/23
2015/05/24 - 2015/05/25 - 2015/05/26 - 2015/05/27 - 2015/05/28 - 2015/05/29 - 2015/05/30
2015/05/31 - 2015/06/01 - 2015/06/02 - 2015/06/03 - 2015/06/04 - 2015/06/05 - 2015/06/06
java.time
You can use the nice java.time classes built into Java 8 and later. Both the above solutions work, this is a way to do in Java 8. Can be done with a little more brevity , split it just for understanding.
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;
public class Clazz {
public static void main(String[] args) throws Exception {
LocalDate today = LocalDate.now();
LocalDate firstDayOfTheMonth = today.with(TemporalAdjusters.firstDayOfMonth());
LocalDate lastDayOfTheMonth = today.with(TemporalAdjusters.lastDayOfMonth());
LocalDate squareCalendarMonthDayStart = firstDayOfTheMonth
.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY));
LocalDate squareCalendarMonthDayEnd = lastDayOfTheMonth
.with(TemporalAdjusters.nextOrSame(DayOfWeek.SATURDAY));
List<LocalDate> totalDates = new ArrayList<>();
while (!squareCalendarMonthDayStart.isAfter(squareCalendarMonthDayEnd)) {
totalDates.add(squareCalendarMonthDayStart);
squareCalendarMonthDayStart = squareCalendarMonthDayStart.plusDays(1);
}
totalDates.forEach(System.out::println);
}
}
Get the monday before the 1st of that month:
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.set(2016, 08, 01);
Calendar start = Calendar.getInstance();
start.setFirstDayOfWeek(Calendar.MONDAY);
start.setWeekDate(2016,c.getWeekYear(), Calendar.MONDAY);
Get the sunday after the last day of that month:
c.set(2016,08,31);
Calendar end = Calendar.getInstance();
end.setFirstDayOfWeek(Calendar.MONDAY);
end.setWeekDate(2016, c.getWeekYear(), Calendar.SUNDAY);
Then print all dates between start and end
Write a common method like this and use it -
fun getAllDateOfCurrentMonth(): List<LocalDate> {
val yearMonth= YearMonth.now()
val firstDayOfTheMonth = yearMonth.atDay(1)
val datesOfThisMonth = mutableListOf<LocalDate>()
for (daysNo in 0 until yearMonth.lengthOfMonth()){
datesOfThisMonth.add(firstDayOfTheMonth.plusDays(daysNo.toLong()))
}
return datesOfThisMonth
}

Find all previous Tuesdays in a given range?

What I need to do in my Android project is to find all the previous Tuesdays for the last three months and put them into a String Array. It appears that neither the Calendar Class nor SimpleDateFormat would work for this.
So for example, today is Tuesday, so it would start today and I'd need to return 2013_8_13, and next in the array would be 2013_8_6, then 2013_7_30, and so on. Am I wrong about the Calendar Class or SimpleDateFormat? If so, could you give me an idea as to how it could be done?
EDIT: Updated answer to go back to a certain day instead of back a certain number of days. Also changed String array to ArrayList
ArrayList<String> tuesdayArrayList = new ArrayList<String>();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_M_d");
Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_WEEK);
Date date = new Date();
Date cutoffDate;
int cutoffYear = 2013;
int cutoffMonth = Calendar.JUNE;
int cutoffDayOfMonth = 25;
cutoffDate = new GregorianCalendar(cutoffYear, cutoffMonth, cutoffDayOfMonth).getTime();
while (day != Calendar.TUESDAY) {
calendar.add(Calendar.DATE, 1);
day = calendar.get(Calendar.DAY_OF_WEEK);
}
int i = 0;
while (date.after(cutoffDate)) {
calendar.add(Calendar.DATE, -7);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
date = new GregorianCalendar(year, month, dayOfMonth).getTime();
tuesdayArrayList.add(dateFormat.format(date));
Log.d("myTag: ", tuesdayArrayList.get(i));
i++;
}

Compare if two dates are within same week in android

I have two dates.Got them from something like......
Calendar c=Calendar.getInstance();
year=c.get(c.YEAR);
month=c.get(c.MONTH);
month++;
date=c.get(c.DATE);
and other date is broken into date2,month2
Now I want to see if both of them are in the same week.
It's possible through lots of calculation and logic.Problem occurs when 1st date is suppose 03 March and 2nd date is 28Feb. Both of them are in same week but difficult to compare/check that. So I want to know if there is any built in function or any way to compare them easily.Please help..........
use something like this:
Calendar c = Calendar.getInstance();
Integer year1 = c.get(c.YEAR);
Integer week1 = c.get(c.WEEK_OF_YEAR);
Calendar c = Calendar.getInstance();
c.setTimeInMillis(/*Second date in millis here*/);
Integer year2 = c.get(c.YEAR);
Integer week2 = c.get(c.WEEK_OF_YEAR);
if(year1 == year2) {
if(week1 == week2) {
//Do what you want here
}
}
This should do it :D
You can get the week number for your date using c.get(Calendar.WEEK_OF_YEAR) and compare the results for your two dates.
Also accessing constants via instance variables (c.YEAR) is not recommended - access them using classes (Calendar.YEAR).
Just posting a slightly modified solution based on #FabianCook and as pointed out by #harshal his solution doesn't cater for two dates on different years but in the same week.
The modification is to actually set the DAY_OF_WEEK in both Calendar dates to point to Monday.....in this case both dates will be set to the same day even if they are in different years and then we can compare them.
Calendar cal1 = Calendar.getInstance();
cal1.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
int year1 = cal1.get(Calendar.YEAR);
int week1 = cal1.get(Calendar.WEEK_OF_YEAR);
Calendar cal2 = Calendar.getInstance();
cal2.setTimeInMillis(/*Second date in millis here*/);
cal2.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
int year2 = cal2.get(Calendar.YEAR);
int week2 = cal2.get(Calendar.WEEK_OF_YEAR);
if(year1 == year2 && week1 == week2){
//Do what you want here
}
Use java.time
You can get it available the following ways:
Java 8+ and Android API 26+: directly available
Java 6 and 7: ThreeTenBP
Android 25 and lower: ThreeTenABP
It is not recommended to use java.util.Calendar and java.util.Date anymore.
How to find out if two given dates are in the same calendar week?
Using plain java.time:
public boolean inSameCalendarWeek(LocalDate firstDate, LocalDate secondDate) {
// get a reference to the system of calendar weeks in your defaul locale
WeekFields weekFields = WeekFields.of(Locale.getDefault());
// find out the calendar week for each of the dates
int firstDatesCalendarWeek = firstDate.get(weekFields.weekOfWeekBasedYear());
int secondDatesCalendarWeek = secondDate.get(weekFields.weekOfWeekBasedYear());
/*
* find out the week based year, too,
* two dates might be both in a calendar week number 1 for example,
* but in different years
*/
int firstWeekBasedYear = firstDate.get(weekFields.weekBasedYear());
int secondWeekBasedYear = secondDate.get(weekFields.weekBasedYear());
// return if they are equal or not
return firstDatesCalendarWeek == secondDatesCalendarWeek
&& firstWeekBasedYear == secondWeekBasedYear;
}
You can do that with simple int values, too:
public static boolean inSameCalendarWeek(int firstYear, int firstMonth, int firstDayOfMonth,
int secondYear, int secondMonth, int secondDayOfMonth) {
// create LocalDates using the integers provided
LocalDate firstDate = LocalDate.of(firstYear, firstMonth, firstDayOfMonth);
LocalDate secondDate = LocalDate.of(secondYear, secondMonth, secondDayOfMonth);
// get a reference to the system of calendar weeks in your defaul locale
WeekFields weekFields = WeekFields.of(Locale.getDefault());
// find out the calendar week for each of the dates
int firstDatesCalendarWeek = firstDate.get(weekFields.weekOfWeekBasedYear());
int secondDatesCalendarWeek = secondDate.get(weekFields.weekOfWeekBasedYear());
/*
* find out the week based year, too,
* two dates might be both in a calendar week number 1 for example,
* but in different years
*/
int firstWeekBasedYear = firstDate.get(weekFields.weekBasedYear());
int secondWeekBasedYear = secondDate.get(weekFields.weekBasedYear());
// return if they are equal or not
return firstDatesCalendarWeek == secondDatesCalendarWeek
&& firstWeekBasedYear == secondWeekBasedYear;
}
In case you have to extend or use legacy code:
public static boolean inSameCalendarWeek(Calendar firstCalendar, Calendar secondCalendar) {
// create LocalDates from Instants created from the given Calendars
LocalDate firstDate = LocalDate.from(firstCalendar.toInstant());
LocalDate secondDate = LocalDate.from(secondCalendar.toInstant());
// get a reference to the system of calendar weeks in your defaul locale
WeekFields weekFields = WeekFields.of(Locale.getDefault());
// find out the calendar week for each of the dates
int firstDatesCalendarWeek = firstDate.get(weekFields.weekOfWeekBasedYear());
int secondDatesCalendarWeek = secondDate.get(weekFields.weekOfWeekBasedYear());
/*
* find out the week based year, too,
* two dates might be both in a calendar week number 1 for example,
* but in different years
*/
int firstWeekBasedYear = firstDate.get(weekFields.weekBasedYear());
int secondWeekBasedYear = secondDate.get(weekFields.weekBasedYear());
// return if they are equal or not
return firstDatesCalendarWeek == secondDatesCalendarWeek
&& firstWeekBasedYear == secondWeekBasedYear;
}
The output of the following code
public static void main(String[] args) {
// a date from calendar week 1 in the week based year 2020
LocalDate janFirst2020 = LocalDate.of(2020, 1, 1);
// another date from calendar week 1 in the week based year 2020
LocalDate decThirtyFirst2019 = LocalDate.of(2019, 12, 31);
System.out.println(inSameCalendarWeek(janFirst2020, decThirtyFirst2019));
// then a third date from calendar week 1, but this time in the week based year 2021
LocalDate janSeventh2021 = LocalDate.of(2021, 1, 7);
System.out.println(inSameCalendarWeek(janSeventh2021, decThirtyFirst2019));
}
is therefore
true
false
in my locale.
It's a java solution. Following code segment checks if two dates are within same week. It also covers edge cases, where week starts in one calendar year (December) and ends in next year (January).
Note: Code has a dependency on joda-time:
compile 'joda-time:joda-time:2.3'
public static boolean isSameWeek(final Date d1, final Date d2) {
if ((d1 == null) || (d2 == null))
throw new IllegalArgumentException("The date must not be null");
return isSameWeek(new DateTime(d1), new DateTime(d2));
}
public static boolean isSameWeek(final DateTime d1, final DateTime d2) {
if ((d1 == null) || (d2 == null))
throw new IllegalArgumentException("The date must not be null");
// It is important to use week of week year & week year
final int week1 = d1.getWeekOfWeekyear();
final int week2 = d2.getWeekOfWeekyear();
final int year1 = d1.getWeekyear();
final int year2 = d2.getWeekyear();
final int era1 = d1.getEra();
final int era2 = d2.getEra();
// Return true if week, year and era matches
if ((week1 == week2) && (year1 == year2) && (era1 == era2))
return true;
// Return false if none of the conditions are satisfied
return false;
}
Test case:
public class TestDateUtil {
#Test
public void testIsSameWeek() {
final DateTime d1 = new DateTime(2014, 12, 31, 0, 0);
final DateTime d2 = new DateTime(2015, 1, 1, 0, 0);
final DateTime d3 = new DateTime(2015, 1, 2, 0, 0);
final DateTime d4 = new DateTime(2015, 1, 8, 0, 0);
assertTrue(isSameWeek(d1, d2));
assertTrue(isSameWeek(d2, d1));
assertTrue(isSameWeek(d2, d3));
assertTrue(isSameWeek(d3, d2));
assertFalse(isSameWeek(d2, d4));
assertFalse(isSameWeek(d4, d2));
assertFalse(isSameWeek(d1, d4));
assertFalse(isSameWeek(d4, d1));
}
}
I ended up using
date1.with(previousOrSame(MONDAY)).equals(date2.with(previousOrSame(MONDAY)))
assuming that weeks start on Monday.
private int weeksBetween(Calendar startDate, Calendar endDate) {
startDate.set(Calendar.HOUR_OF_DAY, 0);
startDate.set(Calendar.MINUTE, 0);
startDate.set(Calendar.SECOND, 0);
int start = (int)TimeUnit.MILLISECONDS.toDays(
startDate.getTimeInMillis())
- startDate.get(Calendar.DAY_OF_WEEK);
int end = (int)TimeUnit.MILLISECONDS.toDays(
endDate.getTimeInMillis());
return (end - start) / 7;
}
if this method returns 0 they are in the same week
if this method return 1 endDate is the week after startDate
if this method returns -1 endDate is the week before startDate
you get the idea
Let's say, a week starts one year and ends the next year and we pick 2 dates from this week so that they are in different years. Then, the accepted answer yields the wrong result as it checks that the dates are in the SAME YEAR!.
To improve the solution, one could obtain a date corresponding to some day (it could be Monday) of its week and then check that both dates belong to the same day. However, before doing so make sure that both Calendar objects are in the SAME time zone. So, set the time zone of one to another. Also, the solution below works for every API level as it doesn't require the usage of getWeekOfWeekyear() or getWeekYear() (these work with API 24 and higher.
public boolean isSameWeek(Calendar calendar1, Calendar calendar2) {
Calendar calendar2Copy = (Calendar) calendar2.clone();
calendar2Copy.setTimeZone(calendar1.getTimeZone());
calendar1.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendar2Copy.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
return calendar1.get(Calendar.YEAR) == calendar2Copy.get(Calendar.YEAR)
&& calendar1.get(Calendar.DAY_OF_YEAR) == calendar2Copy.get(Calendar.DAY_OF_YEAR);
}
this will give true if two dates from same week
fun isEqualWeek(date1: Long, date2: Long):Boolean{
val cal1 = Calendar.getInstance()
val cal2 = Calendar.getInstance()
cal1.time = Date(date1)
cal2.time = Date(date2)
return (cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)) && (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(
Calendar.WEEK_OF_YEAR
))
}
Here in Joda's Library I found that the week starts from Monday, but I wanted the week to start from Sunday, so just used the below function :
public static boolean isSameWeek(final Date initDate, final Date finalDate) {
if (initDate != null && finalDate != null) {
Calendar initCalender = Calendar.getInstance();
Calendar finalCalender = Calendar.getInstance();
initCalender.setTime(initDate);
finalCalender.setTime(finalDate);
if (finalCalender.get(Calendar.YEAR) >= initCalender.get(Calendar.YEAR)) {
//check for same year
if (finalCalender.get(Calendar.YEAR) == initCalender.get(Calendar.YEAR)) {
if (finalCalender.get(Calendar.WEEK_OF_YEAR) == initCalender.get(Calendar.WEEK_OF_YEAR)) {
return true;
}
} else //check whether next corresponding year
if (finalCalender.get(Calendar.YEAR) - initCalender.get(Calendar.YEAR) == 1) {
if (initCalender.get(Calendar.WEEK_OF_YEAR) == 1 || initCalender.get(Calendar.WEEK_OF_YEAR) == 53) {
if (finalCalender.get(Calendar.WEEK_OF_YEAR) == 1) {
if (initCalender.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && finalCalender.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
return true;
}
}
}
}
} else {
throw new IllegalArgumentException("Final Date should be greater or equal to Initial Date");
}
} else {
throw new IllegalArgumentException("The date must not be null");
}
return false;
}

Finding the last pay dates

I've written this simple method to give me the date of every pay period and it has ceased to work as of January first. I'm really not sure what's wrong here. It doesn't return anything.
public static List<Date> getPayPeriodDatesSinceStartOfYear() {
Calendar cal = new GregorianCalendar();
cal.add(Calendar.WEEK_OF_YEAR, 1);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
cal.set(Calendar.WEEK_OF_YEAR, 2);
Calendar currentDate = new GregorianCalendar();
currentDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
int counter = 2;
List<Date> dates = new ArrayList<Date>();
while ((cal.getTime().compareTo((currentDate.getTime())) <= 0)) {
dates.add(cal.getTime());
counter += 2;
cal.set(Calendar.WEEK_OF_YEAR, counter);
}
java.util.Collections.reverse(dates);
if(dates.isEmpty()){
JOptionPane.showMessageDialog(null, "NO DATES, SOMETHING IS WRONG!");
}
return dates;
}
Your while condition is not being met, the way you have it set up cal is greater than currentDate therefore the while loop never happens.
Calendar cal = new GregorianCalendar();
cal.add(Calendar.WEEK_OF_YEAR, 1);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
cal.set(Calendar.WEEK_OF_YEAR, 2);
Why are you setting week to 1 and then to 2?
(cal.getTime().compareTo((currentDate.getTime())) <= 0)
See the doc for Date. It has methods like before(Date when) and after(Date when).

Categories