Counting days in java - java

I don't really know exactly how to explain this but basically the user is asked how many times, say they say 2. It will ask the user to input a month, day and year in numerical form. Then it will do it again because they said 2. It spits out a date in (Saturday, January 8th, 2014) format for each date they put in. So what I want is:
There were X dates on Sunday
There were X dates on Monday
There were X dates on Tuesday
There were X dates on Wednesday
There were X dates on Thursday
There were X dates on Friday
There were X dates on Saturday
How can I make java recognize the day of week and then add one to it so I can replace X above.
I have variables for each day, for example int saturday. I know I have to do saturday++; somewhere but I don't know where. I tried a switch and case but it doesn't know
case Monday:
because Monday is no where in my code, I used a simple date format.
Does this make sense? Should I post my code? Warning its like 300 lines.
As Pshemo said "In short, I want the user to say how many "events" occurred, pass their dates and print how many of then happened in each day of week"

Try to format your SimpleDateFormat using an E, which will output the day of the week. Than compare that Date as a String with your weekdays, e.g. day.equals("Monday").
Reference to SimpleDateFormat: http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

The days of the week are int constants in java.util.Calendar. You can find it using:
int dayOfTheWeek = c.get(Calendar.DAY_OF_WEEK);

Here is some example code using the Joda-Time 2.3 library.
The day-of-week is an interpretation based on the time zone. In Joda-Time, a DateTime object actually knows its own time zone, unlike a java.util.Date which seems to have a time zone but does not. Think about whether you want each DateTime object to use its own time zone to determine day-of-week or you way want to convert the objects to a common time zone for comparison.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
java.util.List<DateTime> dateTimes = new java.util.ArrayList<DateTime>();
dateTimes.add( new DateTime( 2014, 1, 2, 3, 4, 5, timeZone ) ); // Thursday
dateTimes.add( new DateTime( 2014, 1, 3, 3, 4, 5, timeZone ) ); // Friday
dateTimes.add( new DateTime( 2014, 1, 9, 3, 4, 5, timeZone ) ); // Thursday
System.out.println( "Date-Time objects…" );
System.out.println( dateTimes );
// Make a list of 7 elements, one element per each day of week.
// Each element stores a count of events occurring on that day of week.
// Using standard ISO 8601 week, Monday first, Sunday last.
java.util.List<Integer> days = new java.util.ArrayList<Integer>( 7 );
for ( int i = 0; i < 7; i++ ) {
days.add( new Integer( 0 ) ); // Initial all counts to zero.
}
for ( DateTime dateTime : dateTimes ) {
int dayOfWeekNumber = dateTime.getDayOfWeek(); // Retrieve day-of-week number, 1-7. Monday is first.
int index = ( dayOfWeekNumber - 1 ); // Index/Zero-based counting, so subtract 1 from ordinal.
Integer oldIntegerCount = days.get( index ); // Retrieve the previous count for this day-of-week.
Integer newIntegerCount = ( oldIntegerCount + 1 ); // Increment old count to new count object.
days.set( index, newIntegerCount ); // Replace old Integer object with freshly incremented Integer object.
}
// Report results.
// Joda-Time does not have a convenient list of days of week to iterate. So the following code is a bit goofy.
// The java.time.* package in Java 8 does have the nice feature of a fancy Enum for days-of-week.
for ( int i = 0; i < days.size(); i++ ) {
LocalDate date = new LocalDate();
date = date.withDayOfWeek( i + 1 ); // Add one to transform index into ordinal.
System.out.println( "There were " + days.get( i ) + " dates on " + date.dayOfWeek().getAsText() );
}
When run…
Date-Time objects…
[2014-01-02T03:04:05.000+01:00, 2014-01-03T03:04:05.000+01:00, 2014-01-09T03:04:05.000+01:00]
There were 0 dates on Monday
There were 0 dates on Tuesday
There were 0 dates on Wednesday
There were 2 dates on Thursday
There were 1 dates on Friday
There were 0 dates on Saturday
There were 0 dates on Sunday

Related

How to get the first Sunday of the Month given week number and year?

Given a week number and a year, I'd like to be able to compute the first Sunday of that month. I've cobbled together some code that "mostly", but not always, works. Not sure why it doesn't work for every example, but that's why I'm posting. :)
The code below should get the first Sunday of the year, then iterate the number of weeks (the week number) entered. When done, the code should print out that first Sunday's date.
When incorrect, the code prints the previous Sunday, not the apparently correct one.
Suggestions appreciated.
public static void main(String[] args) throws IOException, MessagingException
{
int enteredWeekNumber = 18;
int enteredYear = 2022;
int doyCounter = 1;
LocalDate firstDoy = LocalDate.of(enteredYear, Month.JANUARY, 1);
LocalDate someSunday = firstDoy.with(firstInMonth(DayOfWeek.SUNDAY));
// Loop to get every Sunday by adding Period.ofDays(7) the current Sunday.
while (someSunday.getYear() == enteredYear && doyCounter <= enteredWeekNumber)
{
System.out.println(" *** " + someSunday.
format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)));
someSunday = someSunday.plus(Period.ofDays(7));
doyCounter++;
}
}
tl;dr
org.threeten.extra.YearWeek // Represents a week-based year and week per the ISO 8601 definition.
.of( y , w ) // Pass your week-based year number, and your week (0-52, 0-53).
.atDay( DayOfWeek.MONDAY ) // Returns `LocalDate`, for the date of the first day (Monday) of that year-week.
.with ( // Adjust to another `LocalDate` object, another date.
TemporalAdjusters // Utility class offering implementations of `TemporalAdjuster` interface.
.dayOfWeekInMonth(
1 , // nth day in the month, an ordinal number.
DayOfWeek.SUNDAY // The day-of-week for which we want the date of the nth.
) // Returns an `TemporalAdjuster` object.
) // Returns a `LocalDate` object.
ISO 8601
The ISO 8601 standard defines a year-week as:
Starting on a Monday.
Week # 1 containing the first Thursday of the calendar year.
This means a week-based year:
Has either 52 or 53 complete weeks.
May include a few days from the previous and/or next calendar year.
ThreeTen-Extra
If your definition is the same, then I suggest adding the Three-Ten Extra library to your project.
YearWeek
Doing so gives you access to the YearWeek class.
YearWeek yw = YearWeek.of( y , w ) ;
Tip: Pass around your codebase objects of this class rather than mere int values enteredWeekNumber & enteredYear. Using objects brings type-safety, ensures valid values, and makes your code more self-documenting.
LocalDate
Get the date of the first day of that week.
LocalDate ld = yw.atDay( DayOfWeek.MONDAY ) ;
TemporalAdjuster
Use a TemporalAdjuster to get nth day-of-week of that month date’s month.
Fortunately, the utility class TemporalAdjusters gives us just such an adjuster.
TemporalAdjuster ta = TemporalAdjusters.dayOfWeekInMonth( 1 , DayOfWeek.SUNDAY ) ;
Apply the temporal adjuster to get another LocalDate object. The java.time classes use immutable objects. We get a fresh object rather than altering ("mutating") the original.
LocalDate firstSunday = ld.with( ta ) ;
If you want to get fancy, you could write your own implementation of a TemporalAdjuster to contain this functionality. I’ll leave that as an exercise for the reader.
May be you could try something like below if your Week starts at the first day of the year
int enteredWeekNumber = 22;
int enteredYear = 2022;
LocalDate someSunday = LocalDate.now()
.withYear(enteredYear)
.with(ChronoField.ALIGNED_WEEK_OF_YEAR, enteredWeekNumber)
.with(TemporalAdjusters.firstInMonth(DayOfWeek.SUNDAY));
or somthing like below, if you use ISO standard
LocalDate someSunday2 = LocalDate.now()
.withYear(enteredYear)
.with(WeekFields.ISO.weekOfYear(), enteredWeekNumber)
.with(TemporalAdjusters.firstInMonth(DayOfWeek.SUNDAY));

How can i change year with LocalDate by adding weeks?

Here is my code. This method works only for 1 ( current year). When week number is more than 53, dates start from dates in first week in current year but not the next.
Year has 52 or 53 weeks, so when week is last (52or53) i have 2020-12-28 - 2021-01-03, but when I want get first week of next year (2021-01-04 - 2021-01-10) it outputs me first week from 2020 ( 2019-12-30 - 2020-01-05).
public void showPreviousNextWeekDays(DataBaseHelper dataBaseHelper, long weekChange) {
if (weekChange >= 0) {
LocalDate ld = LocalDate.now().plusWeeks(weekChange);
final long weekNumber = ld.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR); //takes week from current date
LocalDate firstDayOfWeek = ld.ofYearDay(ld.getYear(), (int)weekNumber)
.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, weekNumber)
.with(DayOfWeek.MONDAY);
LocalDate lastDayOfWeek = ld.ofYearDay(ld.getYear(), (int)weekNumber)
.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, weekNumber)
.with(DayOfWeek.SUNDAY);
String firstAndLastDayOfWeek = firstDayOfWeek.toString() + " - " + lastDayOfWeek.toString();
daysArrayAdapter = new ArrayAdapter<DayModel>(getActivity(), android.R.layout.simple_list_item_1, db.NextWeek(weekChange));
daysList.setAdapter(daysArrayAdapter);
How can i go forward with years also by adding weeks?
You are correct that your code is not correct. When I set weekChange to 14 and run today (September 29), I get 2019-12-30 - 2020-01-05 where expected result would be 2021-01-04 - 2020-01-10. Also for 15 and 16 weeks your code goes back to a week in the beginning of this year rather than finding a week in the beginning of next year as it should.
I suggest the following, which is also a bit simpler:
int weekChange = 14;
LocalDate ld = LocalDate.now(ZoneId.systemDefault()).plusWeeks(weekChange);
LocalDate firstDayOfWeek = ld.with(DayOfWeek.MONDAY);
LocalDate lastDayOfWeek = ld.with(DayOfWeek.SUNDAY);
String firstAndLastDayOfWeek = firstDayOfWeek.toString() + " - " + lastDayOfWeek.toString();
System.out.println(firstAndLastDayOfWeek);
Output when run today:
2021-01-04 - 2021-01-10
LocalDate uses the ISO calendar system including ISO weeks if not explicitly instructed otherwise. So we can be sure that ld.with(DayOfWeek.MONDAY) gives us Monday at the start of the same ISO week. Similarly ld.with(DayOfWeek.SUNDAY) gives us Sunday at the end of the ISO week. So there is nothing more to it.
What happened in your code?
Sticking to the case of weekChange 14 and running today.
ld becomes 2021-01-05 (Tuesday 14 weeks from now). This date is in week 1 of 2021, so weekNumber will be 1.
ofYearDay is a static method of LocalDate. So ld.ofYearDay(ld.getYear(), (int)weekNumber) gives you the same date as you would have got from LocalDate.ofYearDay(ld.getYear(), (int)weekNumber). It does not use ld for anything. Since weekNumber is 1, you get day 1 of 2021, so 2021-01-01. Passing the week number as the day of year to ofYearDay() is meaningless. 2021-01-01 happens to fall in week 53 of 2020. So with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, weekNumber) adjusts the date back to week 1 of 2020. This is where we go a year wrong. The result is 2020-01-03. The Monday of that week is 2019-12-30, which explains why you got this as the first day of week in the output.
The last day of week is similar. And week numbers 2 and 3 are similar since you use the week number as a day of year, and January 2 and 3 fall in the last week of the previous year, 2020, too.
How did I find out? I ran your code in my debugger. There it was clear to see. If you haven’t yet learned to use a debugger. I suggest that now is the best of all times.

How to validate the dates displayed are correct?

I need some assistance in try to pretty much assert each date within an element against the actual dates.
Basically I have 5 date tiles in my application that are displayed like so:
Mon 20th May
Tue 21st May
Wed 22nd May
Thu 23rd May
Fri 24th May
Now the elements for these tiles are the same where the day has an element of ‘id=day’ (e.g. Mon, Tue, Wed) and the date has an element of ‘id=date’ (e.g. 20th May, 21st May, 22nd May) etc.
Below explains what I am trying to do:
In the application it always shows 5 dates
The 5 dates shown always starts from tomorrow’s date and shows the next 5 dates excluding Sunday.
I want to perform an assertion to check the 5 days from the date tiles
(e.g. Mon, Tue, Wed) matches the above criteria.
I want to also perform an assertion to check the 5 dates from the date
tiles (e.g. 20th May, 21st May, 22nd May) matches the above criteria.
How can this be achieved?
I have set a little date picker below to start off with but I am not a developer so will require somebody with a little more coding knowledge and logic to help achieve this:
SimpleDateFormat sdf = new SimpleDateFormat("E-dd-MMM");
Calendar cal = Calendar.getInstance();
// get start date
cal.add(Calendar.DAY_OF_YEAR, +1);
// loop adding one day in each iteration
for(int i = 0; i< 5; i++){
cal.add(Calendar.DAY_OF_YEAR, 1);
System.out.println(sdf.format(cal.getTime()));
}
Avoid legacy classes
You are using terrible date-time classes that were supplanted years ago by the java.time classes defined in JSR 310.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. If critical, confirm the zone with your user.
Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.
LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.
Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety. Ditto for Year & YearMonth.
LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
DayOfWeek
If you need to track the day-of-week (not clear in your Question), use the DayOfWeek enum.
DayOfWeek dow = ld.getDayOfWeek() ;
Tile
Your Tile class should hold a member variable of type LocalDate. Use smart objects rather than dumb strings. Generate localized text for display to your users, but your internal business logic should be using objects of types specific to the task.
Your class should implement the overridden toString method to generate text helpful when debugging or logging. Define a separate method named something like getDisplayName to generate text appropriate for display to the user.
public class Tile {
LocalDate localDate ;
static private DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "EEE dd MMM" , Locale.US ) ;
public Tile( LocalDate localDateArg ) {
this.localDate = localDateArg ;
}
public String getDisplayName() {
String output = this.localDate.format( Tile.formatter ) ;
return output ;
}
#Override
public String toString() {
String output = Tile.class.getSimpleName() + "{ localDate:" + this.localDate.toString() + " }" ;
}
}
If you really need the th, st, on your numbers, you will need to take extra steps. This feature is not built into DateTimeFormatter. Search on Stack Overflow for "ordinal date" as this has been covered multiple times already. I suggest adding this feature last, after you have the rest working.
Generating tiles
The 5 dates shown always starts from tomorrow’s date and shows the next 5 dates excluding Sunday.
So we need a list of tiles. For each new tile, discard if found to be a Sunday.
int limit = 5 ;
List< Tile > tiles = new ArrayList<>( limit ) ;
Get today's date. Increment to each next date, omitting Sunday.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
LocalDate tomorrow = LocalDate.now( z ).plusDays( 1 ) ; // Tomorrow is today plus one day.
LocalDate localDate = tomorrow ;
for ( int i = 1 ; i <= limit ; i ++ ) {
if( localDate.getDayOfWeek().equals( DayOfWeek.SUNDAY ) { // If this date is a Sunday…
localDate = localDate.plusDays( 1 ) ; // Omit Sunday, bump to the next date.
}
Tile tile = new Tile( localDate ) ;
tiles.add( tile ) ;
// Set up the next loop.
localDate = localDate.plusDays( 1 ) ;
}
I want to perform an assertion to check the 5 days from the date tiles (e.g. Mon, Tue, Wed) matches the above criteria.
Write a little method to check our collection of tiles. I used logic similar to the method that creates the list of tiles.
public boolean areTilesValidByDate( final List< Tile > tiles ) {
Objects.requireNonNull​( tiles ) ; // Verify we were passed a list.
int limit = 5 ;
if( tiles.size() != limit ) { // If unexpected size, the list cannot be valid.
return false ;
}
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
LocalDate tomorrow = LocalDate.now( z ).plusDays( 1 ) ; // Tomorrow is today plus one day.
LocalDate localDate = tomorrow ;
// Loop through the five dates we expect to find in the existing tiles.
for ( int i = 1 ; i <= limit ; i ++ ) {
if( localDate.getDayOfWeek().equals( DayOfWeek.SUNDAY ) { // If this date is a Sunday…
localDate = localDate.plusDays( 1 ) ; // Omit Sunday, bump to the next date.
}
Tile tile = tiles.get( i - 1 ) ; // Subtract one for annoying zero-based index counting rather than 1-based ordinal counting. Index-counting comes from simplistic array and byte-jumping code in old C-style languages, and is a habit the industry finds difficult to shake off.
if( ! tile.localDate.isEqual( localDate ) {
return false ;
}
// Set up the next loop.
localDate = localDate.plusDays( 1 ) ;
}
// If we make it to this point, the list must be valid.
return true ;
}
In real work, I would not be hard-coding the time zone (the ZoneId).
Caveat: I never ran any of this code. You may need to fix. (⇐ The understatement is a developer joke.)
P.S. If you are making software in use by people, then you are a developer. Welcome to the club.
Tip: Search Stack Overflow thoroughly before posting. I helped you out this time, but perhaps should not have as we generally discourage simple duplicates on this site. All this material has been covered many many times on Stack Overflow. Struggling a bit to pull together various found nuggets will help you learn more.

How many instances of a partial date (month & day) appear in a range, and its day of the week

In Java, how would I go about constructing a utility that would take a range of dates (start and end date) and then would see how many times a given partial date ( the month and day-of-month) appears in that range, and will add an entry to a list for each match.
In my instance, I want to give it a range of say 5 years - starting Jan 1st 2014 and going to Dec 31st 2019. My check date is the 2nd August. I want the method to return the full information about each match of any August 2 of any year in the range. So for 2014 is will return Saturday 2nd August 2014, then Sunday 2nd August 2015 etc and so on.
I've been trying to get something working so far with Joda Time and the default date/calendar classes in Java and I'm just getting myself in a mess.
Thanks,
S
Edit: How silly of me, apologies for not adding my code :(
public static List<Date> getDaysInRange(Date startdate,
Date enddate,
Date checkDate) {
SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
List<Date> dates = new ArrayList<>();
Calendar cal = new GregorianCalendar();
cal.setTime(startdate);
while (cal.getTime().before(enddate)) {
if (sdf.format(cal.getTime()).equals(sdf.format(checkDate))) {
Date result = cal.getTime();
dates.add(result);
}
cal.add(Calendar.DATE, 1);
}
return dates;
}
Date-Only
Since you want only a date without time-of-day and without time zone, use a date-only class. The old java.util.Date/.Calendar classes lack such a class. And those old classes are notoriously troublesome and flawed.
Instead use either:
Joda-Time
java.time, built into Java 8, inspired by Joda-Time.
Joda-Time
Here is some untested code using Joda-Time 2.6.
The main idea is to focus on the small set of possible year numbers rather than test every day of year. In the example below, that means six date-time values to compare rather than thousands. Besides efficiency, the purpose of the code becomes more apparent.
The arguments to your routine should be a month number and a day-of-month number, a pair of ints or Integers, rather than a Date. As seen in this examples two int variables, month and day.
LocalDate start = new LocalDate( 2011, 2, 3 );
LocalDate stop = new LocalDate( 2016, 4, 5 );
int yearStart = start.getYear();
int yearStop = stop.getYear();
int month = 11;
int day = 22;
for ( i = yearStart, i <= yearStop, i++ )
{
LocalDate x = new LocalDate( i, month, day );
boolean matchStart = ( x.isEqual( start ) || x.isAfter( start ) );
boolean matchStop = x.isBefore( stop ); // Half-Open approach where beginning of range is inclusive while ending is exclusive.
if ( matchStart && matchStop )
{
// Add to collection of LocalDate objects.
// Later you can ask each LocalDate object for its day-of-week.
{
}
java.time
The java.time package also offers a LocalDate class. The code would be similar to the above Joda-Time example.
I think using SimpleDateFormat is a bad idea. Use Calendar for comparison directly, like this
cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) && cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH)

How can I compare two Calendar dates?

I have a Java problem where I need to check if an item has expired. This is supposed to check if the item is at least x (x is an integer and can be set to any integer value) months old.
Just to reclarify Supposing I have a pack of eggs, I want to check if it has been 1 months since I added them (dateAdded).
I wrote a simple comparison but it doesn't seem to give the correct response. Here is the code.
public Boolean isEndOfLine() {
Calendar today = Calendar.getInstance();
if(today.compareTo(dateAdded) >= END_OF_LINE) {
return true;
} else {
return false;
}
}
The value of end of line is an integer 12 i.e 12 months.
I do not hold javadoc in my head, but along the lines of:
dateAdded.add(Calendar.Month, END_OF_LINE).compareTo(today) > 0
Here's some similar example code, but using the Joda-Time 2.3 library.
FYI:
A Joda-Time DateTime instance knows its own time zone.
The minusMonths method is smart, handles Daylight Saving Time and other issues. You may want to read its source code to verify its logic follows your business rules as to what "x number of months ago" means.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
// Better to specify a time zone explicitly rather than rely on default.
// Time Zone list… http://joda-time.sourceforge.net/timezones.html (not quite up-to-date, read page for details)
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
int countMonths = 2;
DateTime now = new DateTime( timeZone );
// If you want to include the entire day, get first moment of the day by calling "withTimeAtStartOfDay".
DateTime someMonthsAgo = now.minusMonths( countMonths ).withTimeAtStartOfDay();
DateTime dateAdded = new DateTime( 2013, 5, 6, 7, 8, 9, timeZone ); // Arbitrary values for example.
// If 'dateAdded' happened prior to our target date-time 'someMonthsAgo', the pack of eggs is expired.
Boolean isEndOfLine = dateAdded.isBefore( someMonthsAgo );
Dump to console…
System.out.println( "now: " + now );
System.out.println( "someMonthsAgo: " + someMonthsAgo );
System.out.println( "dateAdded: " + dateAdded );
System.out.println( "isEndOfLine: " + isEndOfLine );
When run…
now: 2014-01-08T21:36:11.179+01:00
someMonthsAgo: 2013-11-08T00:00:00.000+01:00
dateAdded: 2013-05-06T07:08:09.000+02:00
isEndOfLine: true
as mentioned in the Calendar docs
You should not rely on the number returned by compareTo - you just know that if it is greater than 0 that the original date is greater.
So create a new date (x months in the passed) and compare to that one.
The method returns 0 if the time represented by the argument is equal to the time represented by this Calendar object; or a value less than 0 if the time of this Calendar is before the time represented by the argument; or a value greater than 0 if the time of this Calendar is after the time represented.
import java.util.*;
public class CalendarDemo {
public static void main(String[] args) {
// create two calendar at the different dates
Calendar cal1 = new GregorianCalendar(2015, 8, 15);
Calendar cal2 = new GregorianCalendar(2008, 1, 02);
// compare the time values represented by two calendar objects.
int i = cal1.compareTo(cal2);
// return positive value if equals else return negative value
System.out.println("The result is :"+i);
// compare again but with the two calendars swapped
int j = cal2.compareTo(cal);
// return positive value if equals else return negative value
System.out.println("The result is :" + j);
}
}
Here is the working solution. Tested with JUNIT to confirm results.
public Boolean isEndOfLine() {
Calendar today = Calendar.getInstance();
today.add(Calendar.MONTH, -END_OF_LINE);
return today.compareTo(dateAdded) >= 0;
}
I subtracted the END_OF_LINE from today using the add method. Notice the minus on line 3. I then compared to see if it is greater than 0. Thanks for all your suggestions.

Categories

Resources