tl;dr
Use java.time.LocalDate
class.
if ( z.minusDays ( 1 ).isEqual ( y ) && z.minusDays ( 2 ).isEqual ( x ) ) …
Using java.time
The modern approach uses the java.time classes rather than the troublesome old legacy classes Date
& Calendar
.
First convert your array to a list of LocalDate
objects. I changed your example data as I assume you meant the 18th and 19th of February rather than repeating the 18th twice.
String[] dates = {
"2004/1/23" , "2004/1/24" , "2004/1/25" ,
"2004/1/26" , "2004/1/29" , "2004/2/11" ,
"2004/2/17" , "2004/2/18" , "2004/2/19" , "2004/3/7" };
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "uuuu/M/d" );
List < LocalDate > localdates = new ArrayList <> ( dates.length );
for ( String input : dates ) {
LocalDate ld = LocalDate.parse ( input, f );
localdates.add ( ld );
}
Loop the LocalDate
list, remembering the previous two items. If the current and the previous two are all sequential dates, then increment your counter.
Integer tripletCount = 0;
List< LocalDate > tripletDates = new ArrayList<>();
LocalDate x = null;
LocalDate y = null;
for ( LocalDate z : localdates ) {
if ( null == x ) { x = z; continue; }
if ( null == y ) { y = z; continue; }
if ( z.minusDays ( 1 ).isEqual ( y ) && z.minusDays ( 2 ).isEqual ( x ) ) {
tripletCount= ( tripletCount + 1 );
tripletDates.add( z );
}
// Prepare for next loop.
x = y ;
y = z ;
}
Dump to console.
System.out.println ( "localdates: " + localdates );
System.out.println ( "tripletCount: " + tripletCount );
System.out.println ( "tripletDates: " + tripletDates );
localdates: [2004-01-23, 2004-01-24, 2004-01-25, 2004-01-26, 2004-01-29, 2004-02-11, 2004-02-17, 2004-02-18, 2004-02-19, 2004-03-07]
tripletCount: 3
tripletDates: [2004-01-25, 2004-01-26, 2004-02-19]
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.