The Calendar
class is now legacy, supplanted in Java by the java.time classes. For Android, see bullets below.
For a date-only value without time-of-day and without time zone, use LocalDate
.
LocalDate from = LocalDate.of( year , monthOfYear , dayOfMonth ) ;
To get a new value based on an existing value, use a TemporalAdjuster
. The class TemporalAdjusters
provides several handy implementations. Apparently you would want lastDayOfYear
.
LocalDate to = from.with( TemporalAdjusters.lastDayOfYear() ) ;
For Java, I would suggest tracking this pair of LocalDate
objects using the LocalDateRange
class found in the ThreeTen-Extra project. But that code is not back-ported to Android. You might want to create your own simple version of that class to combine the pair.
package com.example.javatimestuff;
import org.threeten.bp.Duration;
import org.threeten.bp.LocalDate;
public class DateRange
{
private LocalDate start, stop;
// private Duration duration ; // Cache value if calling `getDuration` frequently.
// private String stringed ; // Cache value if calling `toString` frequently.
public DateRange ( LocalDate startArg , LocalDate stopArg )
{
this.start = startArg;
this.stop = stopArg;
}
public LocalDate getStart ()
{
return this.start;
}
public LocalDate getStop ()
{
return this.stop;
}
public Period toPeriod ()
{
Period p = Period.between( this.start , this.stop );
return p;
}
@Override
public String toString ()
{
// Per ISO 8601 standard.
// https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
String s = this.start.toString() + "/" + this.stop.toString();
return s;
}
static public LocalDate parse ( String input ) { // Obviously in real work you would make this safer: check for nulls, check for empty string, check for two parts, catch `DateTimeParseException`.
String[] parts = input.split( "/" );
LocalDate start = LocalDate.parse( parts[0]) ;
LocalDate stop = LocalDate.parse( parts[1]) ;
DateRange dr = new DateRange(start , stop ) ;
return dr ;
}
}
Call that class by constructor.
DateRange dr = new DateRange( from , to ) ;
Store in a List
of type DateRange
, our custom class.
List<DateRange> ranges = new ArrayList<>() ;
ranges.add( dr ) ;
For storage, serialize the List
. See: Wikipedia & Oracle Tutorial.
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?